Oma*_*mar 10 c# authentication asp.net-web-api
我有一个自定义委托处理程序来管理请求的身份验证.在我的一个控制器中,不应为特定操作启用身份验证.如何禁用方法和路由的委托处理程序POST api/MyController?
一种选择是对处理程序内的路由进行硬编码,但是,我宁愿将此逻辑保留在处理程序之外.此外,我发现自己将此行为添加到更多操作中,这可能使此方法难以维护.
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Post
&& request.RequestUri.PathAndQuery.StartsWith("/api/MyController"))
return base.SendAsync(request, cancellationToken);
// Do authentication
}
Run Code Online (Sandbox Code Playgroud)
有更好的方法更容易维护吗?
映射路由时,MappHttpRoute存在重载,允许您指定HttpMessageHandler.您可以将处理程序添加到需要它的所有路由中,并将其省略为不应使用它的路由.
有关更多信息,请参阅此链接.以下示例取自此资源:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Route1",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "Route2",
routeTemplate: "api2/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: new MessageHandler2() // per-route message handler
);
config.MessageHandlers.Add(new MessageHandler1()); // global message handler
}
}
Run Code Online (Sandbox Code Playgroud)