我在向其他域上的Web API发出PUT和DELETE CORS请求时遇到一些麻烦.
我已经通过http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#create-webapi-project教程对API进行了编码.
GET和POST请求工作正常,但DELETE和PUT没有.我收到这条消息:
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.
当我在使用ASP.NET Web API的CORS支持PUT和DELETE时向WebConfig添加代码时,我只得到第一个错误.
有人可以帮我这个吗?
您可以添加处理程序来处理此类请求.
创建一个派生自"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); } }
稍后在Register方法的WebApiconfig.cs中添加:
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 . . . }