我使用Asp.Net MVC WebApi 2创建了一个项目。
为了处理PreflightRequests(OPTIONS),我添加了以下代码:
public void ConfigureRoute(HttpConfiguration config)
{
config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE"));
config.MessageHandlers.Add(new PreflightRequestsHandler());
...
}
public class PreflightRequestsHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Headers.Contains("Origin") && request.Method.Method.Equals("OPTIONS"))
{
var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
}
我在https://www.test-cors.org
中测试了我的网站,并获得了200 OK
的OPTIONS方法。
这样看来一切都很好,但是当我测试其他网站的请求时,没有看到任何响应头! check network in this link。但我注意到了这些:
content-length: 0
date: Thu, 02 May 2019 19:22:31 GMT
server:
status: 200
strict-transport-security: max-age=31536000
x-aspnet-version:
x-aspnetmvc-version:
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-powered-by: BeToChe
x-xss-protection: 1; mode=block
我的代码有什么问题?可以删除响应头吗?