標籤:alc const return custom hand token 節點 var efault
解決方案一:
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"; /// <summary> /// 非同步發送 HTTP 要求到要發送到伺服器的內部處理常式 /// </summary> /// <param name="request"></param> /// <param name="cancellationToken"></param> /// <returns></returns> 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(HttpStatusCode.Accepted); response.Headers.Add(AccessControlAllowOrign, request.Headers.GetValues(Origin).FirstOrDefault()); string method = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault(); if (!string.IsNullOrEmpty(method)) { response.Headers.Add(AccessControlAllowMethods, method); } string headers = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders)); if (!string.IsNullOrEmpty(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; }, cancellationToken); } return taskResult; } return base.SendAsync(request, cancellationToken); } }
調用:
調用方式:在Global.asax檔案的Application_Start方法添加GlobalConfiguration.Configuration.MessageHandlers.Add(new CrosHandler());或者在WebApiConfig.cs下面添加:config.MessageHandlers.Add(new CrosHandler());
解決方案二:
在Web.config下的<system.webServer>節點之間添加一下代碼:
<httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Access-Control-Allow-Origin, AppKey, Authorization" /> <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" /> <add name="Access-Control-Request-Methods" value="GET, POST, OPTIONS" /> </customHeaders> </httpProtocol>
C#API解決自訂要求標頭下的跨域問題