Web Api 2处理选项请求 [英] Web Api 2 Handle OPTIONS Requests
问题描述
我在Azure和 AngularJs
forntend上托管了 Web Api 2
后端.我了解到某些 HTTP请求
与 OPTIONS请求
一起使用了预检查.我的问题是如何以这种方式实现后端,如果控制器中有一些动作可以处理以下 GET/POST/PUT/DELETE/... <,那么所有
OPTIONS请求
都将返回200./code>.
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处理选项请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!