2

我正在使用 nuget 包http://nuget.org/packages/AttributeRouting/并为我的 web api 指定了自定义路由。当我尝试在 WebApiConfig 中向我的路由添加自定义委托处理程序 (dh) 时,我的 dh 永远不会被调用。这是有道理的,因为 dh 被分配给默认路由,而不是分配给我用我的 web api 控制器装饰的自定义路由。我可以全局注册 dh 并执行它,但是,我想为每个路由注册自定义 dh(不同的路由需要做不同的事情,我不想将大量逻辑放入一个全局 dh)。

在使用 AttributeRouting 包时,有谁知道如何做到这一点?我已经搜索了网站上的文档,但没有找到任何东西。

任何帮助深表感谢。谢谢!

4

1 回答 1

0

According to the AttributeRouting website, it does not support some features under WebApi, including custom handlers. Think you might be out of luck.

Beware! Due to integration issues with the Web API WebHost framework, the following features will not work:

performance enhancements when matching routes, custom route handlers, querystring parameter constraints, subdomain routing, localization applied to inbound/outbound urls, and lowercasing, appending prefixes, etc to generated routes. These features all have to wait for vNext of the Web API.

If you don't need all the extensive routing that AttibuteRouting provides, you could use your own route attribute and then register routes based on that during startup. e.g.:

public class RouteAttribute : Attribute
{
    public string Value { get; private set; }

    public RouteAttribute (string value)
    {
        Value = value;
    }
}

then register routes based on decorating class or action in your controller:

    foreach (var controllerType in controllers)
        {
        var attributes = System.ComponentModel.TypeDescriptor.GetAttributes(controllerType);
        var uriattribute = (RouteAttribute)attributes[typeof(RouteAttribute)];
        var controllerName = controllerType.Name.Replace("Controller", "");

        string uri = uriattribute.Value;

        config.Routes.MapHttpRoute(
            name: controllerName,
            routeTemplate: uri,
        handler: new YourCustomHandler()
        }
    }

Obviously you don't want to rewrite AttributeRouting, but if your needs are simple it could be an option.

于 2013-04-03T04:52:30.280 回答