Web Api 2 处理 OPTIONS 请求

Web Api 2 Handle OPTIONS Requests(Web Api 2 处理 OPTIONS 请求)
本文介绍了Web Api 2 处理 OPTIONS 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 Web Api 2 后端托管在 Azure 和 AngularJs forntend.我了解某些 HTTP 请求 使用 OPTIONS 请求 进行预检查.我的问题是如何以这种方式实现后端,如果控制器中有一些操作将处理以下 GET/POST/PUT/DELETE/....

I have Web Api 2 backend hosted on Azure and AngularJs forntend. I understand that some of HTTP request use pre-check with OPTIONS request. My question is how to implement backend that way, that all OPTIONS requests will return 200 if there is some action in controller that will handle following GET/POST/PUT/DELETE/....

推荐答案

解决此任务的非优雅方法是手动添加每个控制器

Non elegant way to solve this task is adding in each controller manually

[AcceptVerbs("OPTIONS")]
public HttpResponseMessage Options()
{
    var resp = new HttpResponseMessage(HttpStatusCode.OK);
    resp.Headers.Add("Access-Control-Allow-Origin", "*");
    resp.Headers.Add("Access-Control-Allow-Methods", "GET,DELETE");

    return resp;
}

或者覆盖 MessageHandlers

 public class OptionsHttpMessageHandler : DelegatingHandler
{
  protected override Task<HttpResponseMessage> SendAsync(
  HttpRequestMessage request, CancellationToken cancellationToken)
  {
    if (request.Method == HttpMethod.Options)
      {
         var apiExplorer = GlobalConfiguration.Configuration.Services.GetApiExplorer();

          var controllerRequested = request.GetRouteData().Values["controller"] as string;              
          var supportedMethods = apiExplorer.ApiDescriptions.Where(d => 
             {  
                var controller = d.ActionDescriptor.ControllerDescriptor.ControllerName;
                return string.Equals(
                    controller, controllerRequested, StringComparison.OrdinalIgnoreCase);
            })
          .Select(d => d.HttpMethod.Method)
          .Distinct();

      if (!supportedMethods.Any())
         return Task.Factory.StartNew(
             () => request.CreateResponse(HttpStatusCode.NotFound));

      return Task.Factory.StartNew(() =>
        {
            var resp = new HttpResponseMessage(HttpStatusCode.OK);
            resp.Headers.Add("Access-Control-Allow-Origin", "*");
            resp.Headers.Add(
                "Access-Control-Allow-Methods", string.Join(",", supportedMethods));

            return resp;
        });
}

return base.SendAsync(request, cancellationToken);

  }
}

然后在配置中

GlobalConfiguration.Configuration.MessageHandlers.Add(new OptionsHttpMessageHandler());

即使是第二个选项也不是完美的……不支持原生构建

even second option is not perfect though... no native build in support

这篇关于Web Api 2 处理 OPTIONS 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)