在ajax对webapi进行CORS跨域访问过程中,如果自定义header,浏览器会发出一个options的请求。
询问浏览器是否支持自定义的header类型。
webapi需要做如下处理,才能正常返回浏览器请求
1 在global中对options方法进行预处理,返回服务支持的header类型
protected void Application_BeginRequest(object sender, EventArgs e) { var res = HttpContext.Current.Response; var req = HttpContext.Current.Request; //自定义header时进行处理 if (req.HttpMethod == "OPTIONS") { res.AppendHeader("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name,Token,Cookie"); res.AppendHeader("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS"); res.StatusCode = 200; res.End(); } }
2 在Web.config中设置跨域参数
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="*" /> <add name="Access-Control-Allow-Methods" value="*" /> </customHeaders> </httpProtocol>
3 浏览器经过预处理请求后即可自动访问原始请求,请求调用顺序如下
OPTIONS预处理请求:
OPTIONS http://localhost:8225/api/UserInfo/QueryUserByParam/ HTTP/1.1 Host: localhost:8225 Connection: keep-alive Access-Control-Request-Method: POST Origin: http://localhost:5964 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36 Access-Control-Request-Headers: accept, content-type, token Accept: */* Referer: http://localhost:5964/Page/UserPage.aspx Accept-Encoding: gzip, deflate, sdch Accept-Language: zh-CN,zh;q=0.8
预处理请求成功:
HTTP/1.1 200 OK Server: Microsoft-IIS/10.0 Access-Control-Allow-Headers: Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name,Token,Cookie Access-Control-Allow-Methods: POST,GET,PUT,PATCH,DELETE,OPTIONS X-SourceFiles: =?UTF-8?B?RDpcQ29kZVx0b2dvXOa6kOS7o+eggVx0cnVua1xUb2dvXDAxLlRvR28uV2ViQXBpXGFwaVxVc2VySW5mb1xRdWVyeVVzZXJCeVBhcmFtXA==?= X-Powered-By: ASP.NET Access-Control-Allow-Origin: * Access-Control-Allow-Headers: * Access-Control-Allow-Methods: * Date: Tue, 22 Dec 2015 15:19:22 GMT Content-Length: 0
浏览器自动发出原始请求:
GET http://localhost:8225/api/Common/GetUserTypes HTTP/1.1 Host: localhost:8225 Connection: keep-alive Accept: */* Origin: http://localhost:5964 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36 Token: dQTvMagtBk2cJg5WrpmcKQ Referer: http://localhost:5964/Page/UserPage.aspx Accept-Encoding: gzip, deflate, sdch Accept-Language: zh-CN,zh;q=0.8