简体   繁体   English

ASP.NET WebAPI 2路由

[英]ASP.NET WebAPI 2 Routing

I just have one quick question about what seems to have been a limitation with ASP.NET Web API Attribute Routing, but hoping I just suck at research. 我只是对有关ASP.NET Web API属性路由的局限性有一个简短的问题,但希望我能从研究中受益。 In my controller, I'm trying to do something like this: 在我的控制器中,我正在尝试执行以下操作:

public class OrdersController : ApiController
{
    [HttpGet]
    [Route("{apiRoot}/customers/{id:int}/orders")]
    public IHttpActionResult GetCustomerOrders(int id) {...}
}

Where {apiRoot} is defined in either a configuration file. {apiRoot}在其中一个配置文件中定义的位置。

This may not actually be necessary, but I'd like to know how to put a specific path in the route attribute without having to code a static path. 这实际上可能不是必需的,但是我想知道如何在路由属性中放入特定路径而不必编写静态路径。 Is the general idea here supposed to be that you only put text into the route path, except for your parameters which go in {} ? 这里的一般想法是,除了{}参数外,您只将文本放入路径中吗?

How about switching to using a RoutePrefix: 如何切换到使用RoutePrefix:

[MyRoutePrefix]
public class OrdersController : ApiController
{
    [HttpGet]
    [Route("customers/{id:int}/orders")]
    public IHttpActionResult GetCustomerOrders(int id) {...}
}

public class MyRoutePrefixAttribute : RoutePrefixAttribute
{
    public MyRoutePrefixAttribute() 
    {
        Prefix = "the route prefix";
    }
}

RoutePrefixAttribute isn't sealed like RouteAttribute so extending it should allow you do what you need. RoutePrefixAttribute不像RouteAttribute那样密封,因此对其进行扩展应该可以满足您的需求。 Assuming, of course, that all of the controllers in a single class using the same root path. 当然,假设一个类中的所有控制器都使用相同的根路径。

Note: I haven't had a chance to try this but given what I know of attribute routing, I don't see why it shouldn't work. 注意:我没有机会尝试此操作,但是鉴于我对属性路由的了解,我不知道为什么它不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM