概述
ASP.NET Web API 的好用使用過(guò)的都知道,沒(méi)有復(fù)雜的配置文件,一個(gè)簡(jiǎn)單的ApiController加上需要的Action就能工作。但是在使用API的時(shí)候總會(huì)遇到跨域請(qǐng)求的問(wèn)題,特別各種APP萬(wàn)花齊放的今天,API的跨域請(qǐng)求是不能避免的。
在默認(rèn)情況下,為了防止CSRF跨站的偽造攻擊(或者是 javascript的同源策略(Same-Origin Policy)),一個(gè)網(wǎng)頁(yè)從另外一個(gè)域獲取數(shù)據(jù)時(shí)就會(huì)收到限制。有一些方法可以突破這個(gè)限制,那就是大家熟知的JSONP, 當(dāng)然這只是眾多解決方法中一種,由于JSONP只支持GET的請(qǐng)求,如今的復(fù)雜業(yè)務(wù)中已經(jīng)不能滿足需求。而CORS(Cross Origin Resource Sharing https://www.w3.org/wiki/CORS)跨域資源共享,是一種新的header規(guī)范,可以讓服務(wù)器端放松跨域的限制,可以根據(jù)header來(lái)切換限制或者不限制跨域請(qǐng)求。重要的是它支持所有http請(qǐng)求方式。
問(wèn)題
XMLHttpRequest 跨域 POST或GET請(qǐng)求 ,請(qǐng)求方式會(huì)自動(dòng)變成OPTIONS的問(wèn)題。
由于CORS(cross origin resource share)規(guī)范的存在,瀏覽器會(huì)首先發(fā)送一次options嗅探,同時(shí)header帶上origin,判斷是否有跨域請(qǐng)求權(quán)限,服務(wù)器響應(yīng)access control allow origin的值,供瀏覽器與origin匹配,如果匹配則正式發(fā)送post請(qǐng)求,即便是服務(wù)器允許程序跨域訪問(wèn),若不支持 options 請(qǐng)求,請(qǐng)求也會(huì)死掉。
原因
瀏覽器為了安全起見(jiàn),會(huì)Preflighted Request的透明服務(wù)器驗(yàn)證機(jī)制支持開(kāi)發(fā)人員使用自定義的頭部、GET或POST之外的方法,以及不同類(lèi)型的主題內(nèi)容,也就是會(huì)先發(fā)送一個(gè) options 請(qǐng)求,
問(wèn)問(wèn)服務(wù)器是否會(huì)正確(允許)請(qǐng)求,確保請(qǐng)求發(fā)送是安全的。
出現(xiàn) OPTIONS 的情況一般為:
1、非GET 、POST請(qǐng)求
2、POST請(qǐng)求的content-type不是常規(guī)的三個(gè):application/x- www-form-urlencoded(使用 HTTP 的 POST 方法提交的表單)、multipart/form-data(同上,但主要用于表單提交時(shí)伴隨文件上傳的場(chǎng)合)、text/plain(純文本)
3、POST請(qǐng)求的payload為text/html
4、設(shè)置自定義頭部
OPTIONS請(qǐng)求頭部中會(huì)包含以下頭部:Origin、Access-Control-Request-Method、Access-Control-Request-Headers,發(fā)送這個(gè)請(qǐng)求后,服務(wù)器可以設(shè)置如下頭部與瀏覽器溝通來(lái)判斷是否允許這個(gè)請(qǐng)求。
Access-Control-Allow-Origin、Access-Control-Allow-Method、Access-Control-Allow-Headers
解決方法
此方法功能強(qiáng)大,可以解決ASP.NET Web API復(fù)雜跨域請(qǐng)求,攜帶復(fù)雜頭部信息,正文內(nèi)容和授權(quán)驗(yàn)證信息
方法一
public class CrosHandler:DelegatingHandler
{
private const string Origin = "Origin";
private const string AccessControlRequestMethod = "Access-Control-Request-Method";
private const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
private const string AccessControlAllowOrign = "Access-Control-Allow-Origin";
private const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
private const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
private const string AccessControlAllowCredentials = "Access-Control-Allow-Credentials";
protected override TaskHttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCrosRequest = request.Headers.Contains(Origin);
bool isPrefilightRequest = request.Method == HttpMethod.Options;
if (isCrosRequest)
{
TaskHttpResponseMessage> taskResult = null;
if (isPrefilightRequest)
{
taskResult = Task.Factory.StartNewHttpResponseMessage>(() =>
{
HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrign,
request.Headers.GetValues(Origin).FirstOrDefault());
string method = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (method != null)
{
response.Headers.Add(AccessControlAllowMethods, method);
}
string headers = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrWhiteSpace(headers))
{
response.Headers.Add(AccessControlAllowHeaders, headers);
}
response.Headers.Add(AccessControlAllowCredentials, "true");
return response;
}, cancellationToken);
}
else
{
taskResult = base.SendAsync(request, cancellationToken).ContinueWithHttpResponseMessage>(t =>
{
var response = t.Result;
response.Headers.Add(AccessControlAllowOrign,
request.Headers.GetValues(Origin).FirstOrDefault());
response.Headers.Add(AccessControlAllowCredentials, "true");
return response;
});
}
return taskResult;
}
return base.SendAsync(request, cancellationToken);
}
}
使用方式,在Global.asax文件添加
protected void Application_Start()
{
IOCConfig.RegisterAll();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.MessageHandlers.Add(new CrosHandler());
}
方法二
配置文件中添加如下配置,此方法簡(jiǎn)單,應(yīng)對(duì)簡(jiǎn)單的跨域請(qǐng)求
system.webServer>
httpProtocol>
customHeaders>
add name="Access-Control-Allow-Origin" value="*" />
add name="Access-Control-Allow-Headers" value="Content-Type" />
add name="Access-Control-Allow-Methods" value="GET, POST,OPTIONS" />
/customHeaders>
/httpProtocol>
system.webServer>
總結(jié)
以上所述是小編給大家介紹的基于CORS實(shí)現(xiàn)WebApi Ajax 跨域請(qǐng)求解決方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
您可能感興趣的文章:- Apache中配置支持CORS(跨域資源共享)實(shí)例
- 跨域資源共享 CORS 詳解
- 淺析jsopn跨域請(qǐng)求原理及cors(跨域資源共享)的完美解決方法
- JS跨域解決方案之使用CORS實(shí)現(xiàn)跨域
- js實(shí)現(xiàn)跨域的幾種方法匯總(圖片ping、JSONP和CORS)
- 跨域請(qǐng)求的完美解決方法(JSONP, CORS)
- 跨域請(qǐng)求兩種方法 jsonp和cors的實(shí)現(xiàn)
- 你可能不知道的CORS跨域資源共享