XMLHttpRequest 跨域 POST或GET請求 ,請求方式會自動變成OPTIONS的問題。
由于CORS(cross origin resource share)規(guī)范的存在,瀏覽器會首先發(fā)送一次options嗅探,同時(shí)header帶上origin,判斷是否有跨域請求權(quán)限,服務(wù)器響應(yīng)access control allow origin的值,供瀏覽器與origin匹配,如果匹配則正式發(fā)送post請求,即便是服務(wù)器允許程序跨域訪問,若不支持 options 請求,請求也會死掉。
瀏覽器為了安全起見,會Preflighted Request的透明服務(wù)器驗(yàn)證機(jī)制支持開發(fā)人員使用自定義的頭部、GET或POST之外的方法,以及不同類型的主題內(nèi)容,也就是會先發(fā)送一個(gè) options 請求,
問問服務(wù)器是否會正確(允許)請求,確保請求發(fā)送是安全的。
出現(xiàn) OPTIONS 的情況一般為:
1、非GET 、POST請求
2、POST請求的content-type不是常規(guī)的三個(gè):application/x- www-form-urlencoded(使用 HTTP 的 POST 方法提交的表單)、multipart/form-data(同上,但主要用于表單提交時(shí)伴隨文件上傳的場合)、text/plain(純文本)
3、POST請求的payload為text/html
4、設(shè)置自定義頭部
OPTIONS請求頭部中會包含以下頭部:Origin、Access-Control-Request-Method、Access-Control-Request-Headers,發(fā)送這個(gè)請求后,服務(wù)器可以設(shè)置如下頭部與瀏覽器溝通來判斷是否允許這個(gè)請求。
Access-Control-Allow-Origin、Access-Control-Allow-Method、Access-Control-Allow-Headers
解決方法
此方法功能強(qiáng)大,可以解決ASP.NET Web API復(fù)雜跨域請求,攜帶復(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 Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCrosRequest = request.Headers.Contains(Origin);
bool isPrefilightRequest = request.Method == HttpMethod.Options;
if (isCrosRequest)
{
Task<HttpResponseMessage> taskResult = null;
if (isPrefilightRequest)
{
taskResult = Task.Factory.StartNew<HttpResponseMessage>(() =>
{
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).ContinueWith<HttpResponseMessage>(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());
}
方法二
配置文件中添加如下配置,此方法簡單,應(yī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>