如何将委托处理程序限制为Web API中的特定路由?

时间:2013-12-29 18:36:26

标签: 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
}

是否有更好的维护方式?

1 个答案:

答案 0 :(得分:8)

映射路由时,存在MappHttpRoute的重载,允许您指定HttpMessageHandler。您可以将处理程序添加到需要它的所有路由中,并将其省略为不应使用它的路由 有关详细信息,请参阅此link。以下示例取自此资源:

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
    }
}