我有一些麻烦,使PUT和DELETE CORS请求对其他域的Web API。
I have some trouble make PUT and DELETE CORS request to Web API on other domain.
我已经通过教程的http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#create-webapi-project.
GET和POST请求工作正常,但DELETE和PUT没有。我得到这个消息:
GET and POST Requests works fine, but DELETE and PUT doesn't. I get this message:
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource.
当我加code到WebConfig建议在CORS为支持PUT和DELETE用的ASP.NET Web API ,我只得到第一个错误。
When I add code to WebConfig suggested on CORS support for PUT and DELETE with ASP.NET Web API , I get only first error.
谁能帮我这个好吗?
您可以添加一个处理程序来处理这种类型的请求。
You can add a handler to deal with this type of request.
创建一个类从DelegatingHandler推导:
Create a class derive from "DelegatingHandler":
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 };
// Define and add values to variables: origins, headers, methods (can be global)
response.Headers.Add("Access-Control-Allow-Origin", origins);
response.Headers.Add("Access-Control-Allow-Headers", headers);
response.Headers.Add("Access-Control-Allow-Methods", methods);
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
}
后来在注册方法WebApiconfig.cs补充一点:
Later in WebApiconfig.cs in Register method add this:
public static void Register(HttpConfiguration config)
{
// Define and add values to variables: origins, headers, methods (can be global)
// Enable global CORS
config.EnableCors(new EnableCorsAttribute(origins, headers, methods));
// Add handler to deal with preflight requests, this is the important part
config.MessageHandlers.Add(new PreflightRequestsHandler()); // Defined above
.
.
.
}