我用下面,對我工作正常(認爲不能確定「4.0客戶端配置文件」位):
public class CorsHandler : 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 AccessControlAllowOrigin = "Access-Control-Allow-Origin";
private const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
private const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
}
string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
}
var tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(response);
return tcs.Task;
}
return base.SendAsync(request, cancellationToken).ContinueWith(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
return base.SendAsync(request, cancellationToken);
}
}
請記住,在你進行註冊程序啓動(我在Global.asax中)
GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
我面臨着與user3409920所述相同的問題。當我嘗試你的解決方案時,它在'if(isCorsRequest)'內部的'return base.SendAsync(...)'語句上拋出StackOverFlow異常。你有解決這個問題的想法嗎? –
嘿,那裏,只嘗試使用上面的這些返回語句之一。正如你所看到的,第一個將Headers返回到一起,而另一個不會。讓我知道你的投入。乾杯 – felipekm