Web Api 2 处理 OPTIONS 请求 [英] Web Api 2 Handle OPTIONS Requests

查看:28
本文介绍了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 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆