Mac*_*ver 11 c# asp.net-web-api
我有一个自定义路由处理程序,我想在不同的控制器上使用.现在我让控制器使用这个路由处理程序的唯一方法就是设置它
RouteTable.Routes.MapHttpRoute(
name: "CustomRouteHandler",
routeTemplate: "/custom/{controller}/{action}",
defaults: new { id = RouteParameter.Optional, action = RouteParameter.Optional }
).RouteHandler = new CustomRouteHandler();
Run Code Online (Sandbox Code Playgroud)
我真的想使用像这样的路由属性
[HttpGet]
[Route(Name = "GetCart")]
public Cart Get()
{
return _repository.Get();
}
Run Code Online (Sandbox Code Playgroud)
但是,当我使用路由属性时,似乎无法弄清楚如何确保我使用自定义路由处理程序.优选我只会使用路由属性,所以如果我可以使用像"RouteHandler"这样的属性,这里指向我的"CustomRouteHandler",这将是完美的.
是否有一个属性,我可以使用这样我也可以以某种方式指向一个MapHttpRoute万事成"/自定义",然后使用从这里路由属性,使所有控制器都具有自定义处理程序?
另一种选择可能是使我自己的属性,使控制器或方法使用我的自定义路由处理程序?
我试图做一个真正的晶莹剔透的方式为开发者看到,这个控制器或方法是使用自定义routehandler,如果新的开发人员应该增加一个控制器,他们可以只使用像"/自定义"一种特殊的路由或使用属性.
任何想法都非常受欢迎.谢谢.
小智 8
不幸的是,AttributeRouting由于某些限制,这在纯粹方面是不可能的:
谨防!由于Web API WebHost框架的集成问题,以下功能将不起作用:
匹配路由,自定义路由处理程序,查询字符串参数约束,子域路由,应用于入站/出站URL的本地化以及对生成的路由进行小写,附加前缀等时的性能增强.这些功能都必须等待Web API的vNext.
所以你只有三个选择.
1)WebApiConfig.cs以经典方式进行路由:
config.Routes.MapHttpRoute(
name: "GetData",
routeTemplate: "api/yourawesomecontroller/data",
defaults: new { controller = "YourAwesomeController", action = nameof(YourAwesomeController.GetData) },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) },
handler: new YourCustomMessageHandler() { InnerHandler = new HttpControllerDispatcher(config) }
);
Run Code Online (Sandbox Code Playgroud)
2)您也可以注册YourCustomMessageHandler所有请求并在处理程序本身内实现路由过滤:
class YourCustomMessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Get &&
request.RequestUri.PathAndQuery.StartsWith("/api/yourawesomecontroller/data"))
// ... custom handling for request ...
var response = await base.SendAsync(request, cancellationToken);
// ... custom handling for response ...
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
3)最后一个选项是自定义路由属性:
public class MyRouteAttribute : Attribute
{
public string Url { get; private set; }
public MyRouteAttribute (string url)
{
Url = url;
}
}
Run Code Online (Sandbox Code Playgroud)
你需要用它来装饰动作方法.但在这种情况下,您需要在自定义引导程序中注册类似于选项1)的路由,如下所示:
foreach (var controllerType in allControllerTypes)
{
var attributes = System.ComponentModel.TypeDescriptor.GetAttributes(controllerType);
var urlAttribute = (MyRouteAttribute) attributes[typeof(MyRouteAttribute)];
var controllerName = controllerType.Name.Replace("Controller", "");
config.Routes.MapHttpRoute(
name: controllerName,
routeTemplate: urlAttribute.Url,
handler: new YourCustomMessageHandler() { InnerHandler = new HttpControllerDispatcher(config) }
);
}
Run Code Online (Sandbox Code Playgroud)
请注意,您必须明确指定InnerHandler,YourCustomMessageHandler以便将请求传递给管道到其他处理程序和控制器.有关详细信息,请参阅Microsoft说
| 归档时间: |
|
| 查看次数: |
1690 次 |
| 最近记录: |