.NET Web API CORS PreFlight请求

前端之家收集整理的这篇文章主要介绍了.NET Web API CORS PreFlight请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有麻烦使PUT和DELETE CORS请求到其他域上的Web API.

我已经通过http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#create-webapi-project教程编写了API.

GET和POST请求工作正常,但DELETE和PUT不.我收到这个消息:

  1. Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
  2. Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当我添加代码到WebConfig建议在CORS support for PUT and DELETE with ASP.NET Web API,我只得到第一个错误.

有人可以帮我吗

解决方法

您可以添加一个处理程序来处理这种类型的请求.

创建一个派生自“DelegatingHandler”的类:

  1. public class PreflightRequestsHandler : DelegatingHandler
  2. {
  3. protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
  4. {
  5. if (request.Headers.Contains("Origin") && request.Method.Method.Equals("OPTIONS"))
  6. {
  7. var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
  8. // Define and add values to variables: origins,headers,methods (can be global)
  9. response.Headers.Add("Access-Control-Allow-Origin",origins);
  10. response.Headers.Add("Access-Control-Allow-Headers",headers);
  11. response.Headers.Add("Access-Control-Allow-Methods",methods);
  12. var tsc = new TaskCompletionSource<HttpResponseMessage>();
  13. tsc.SetResult(response);
  14. return tsc.Task;
  15. }
  16. return base.SendAsync(request,cancellationToken);
  17. }
  18.  
  19. }

后来在WebApiconfig.cs中的Register方法添加

  1. public static void Register(HttpConfiguration config)
  2. {
  3. // Define and add values to variables: origins,methods (can be global)
  4. // Enable global CORS
  5. config.EnableCors(new EnableCorsAttribute(origins,methods));
  6.  
  7. // Add handler to deal with preflight requests,this is the important part
  8. config.MessageHandlers.Add(new PreflightRequestsHandler()); // Defined above
  9. .
  10. .
  11. .
  12. }

猜你在找的HTML相关文章