【问题标题】:web api single custom routing for all actions所有操作的 web api 单一自定义路由
【发布时间】:2016-06-01 12:52:08
【问题描述】:

我的 web api 控制器中有五个操作,如下所示。

http://localhost:1234/products - 映射getallproduct 动作
http://localhost:1234/products/1 - 映射getproductnyid 动作
http://localhost:1234/products - saveproduct 动作(发布)
http://localhost:1234/products/1/getcolor - getproductcolorbyid动作
http://localhost:1234/products/1/getcost - getproductcostbyid 动作

我需要只有一个自定义路由网址。

我尝试了以下路由,但它在 url(http://localhost:24007/product/GetProductByID/Id) 中附加了我不想要的操作名称。

config.Routes.MapHttpRoute(
    name: "ProductRoute",
    routeTemplate: "product/{action}/{productId}",
    defaults: new { controller = "Product", productId= RouteParameter.Optional }
);

【问题讨论】:

    标签: c# api asp.net-web-api routing url-routing


    【解决方案1】:

    如果你想要这种灵活性,你必须使用属性路由:

    [RoutePrefix("products")]
    public class ProductsController : ApiController {
    
        [HttpGet]
        [Route("")]
        public IHttpActionResult GetAllProduct()
        {
            //...
        }
    
        [HttpGet]
        [Route("{productId}")]
        public IHttpActionResult GetProductById(int id)
        {
            //...
        }
    
        [HttpPost]
        [Route("")]
        public IHttpActionResult SaveProduct(Product product)
        {
            //...
        }
    
        [HttpGet]
        [Route("{productId}/getcolor")]
        public IHttpActionResult GetProductColorById(int id)
        {
            //...
        }
    
        [HttpGet]
        [Route("{productId}/getcost")]
        public IHttpActionResult GetProductCostById(int id)
        {
            //...
        }
    }
    

    记得在你的 HttpConfiguration 对象中注册它们:

    config.MapHttpAttributeRoutes();
    

    顺便说一句:如果您正在设计一个 RESTful API(在我看来),我强烈建议您避免在 URI 中使用类似 RPC 的操作(例如,永远不要使用像 getcolorgetcost 这样的 URI 段) ,但使用符合 REST 约束的名称:

    http://localhost:1234/products/1/color
    http://localhost:1234/products/1/cost
    

    这可以通过更改您的RouteAttributes 来实现:

    [Route("{productId}/color")]
    //...
    [Route("{productId}/cost")]
    

    【讨论】:

    • 谢谢。根据要求,我们不应该使用属性路由
    • 恐怕你别无选择。
    • 你能解释一下为什么不应该使用像getcolors、getcost这样的url吗?
    • 任何 RESTful URI 都应该只代表一个资源。对该资源的操作(动词、意图等)只能使用 HTTP 方法(GET、POST、PUT 等)来表达。 This post 可能有用,this resource 也可以帮助进一步阐明 REST API URI 设计方法。
    猜你喜欢
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多