ASP NET的Web API路线模板 [英] ASP NET Web API Route templates

查看:197
本文介绍了ASP NET的Web API路线模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下API名为机构的实体

I have an entity named Agency with following apis

GET     http://localhost:37331/api/agency?start=1&limit=10&status=1
GET     http://localhost:37331/api/agency/2
POST    http://localhost:37331/api/agency 
PUT     http://localhost:37331/api/agency
DELETE  http://localhost:37331/api/agency/4
POST    http://localhost:37331/api/agency/activate/3
POST    http://localhost:37331/api/agency/deactivate/3
GET     http://localhost:37331/api/agency/types

我使用的路由模板

The route templates I used are

        config.Routes.MapHttpRoute(
            name: "ControllerActionIdApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { },
            constraints: new { id = @"\d+" }
        );
        //
        config.Routes.MapHttpRoute(
            name: "ControllerActionApi",
            routeTemplate: "api/{controller}/{action}"
        );
        //
        config.Routes.MapHttpRoute(
            name: "ControllerIdApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { },
            constraints: new { id = @"\d+" }
        );
        //
        config.Routes.MapHttpRoute(
            name: "ControllerApi",
            routeTemplate: "api/{controller}"
        );

显然,是第二和第三之间的暧昧。我有一个变通方法,把ID为查询字符串

Obviously there is ambiguous between the 2nd and 3rd. I do have a workaround that put the id into query string

GET     http://localhost:37331/api/agency?id=2
DELETE  http://localhost:37331/api/agency?id=4

我认为必须有聪明的办法。能否请你说明一下吗?

I think there must be smart way. Could you please suggest on this?

感谢

推荐答案

在序列匹配的路由。您的约束:新{ID = @\\ D +}第三路线没有得到一个查找,因为第二个途径将永远是赢家。

The routes are matched in sequence. Your constraint: new { id = @"\d+" } on the 3rd route isn't getting a look-in because the 2nd route will always win.

所以,交换你的第二个和第三个左右的路线。

So swap your 2nd and 3rd routes around.

始终把最有选择性的路线在顶部。

Always put the most selective routes at the top.

    config.Routes.MapHttpRoute(
        name: "ControllerActionIdApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { },
        constraints: new { id = @"\d+" }
    );
    //

    config.Routes.MapHttpRoute(
        name: "ControllerIdApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { },
        constraints: new { id = @"\d+" }
    );
    //
    config.Routes.MapHttpRoute(
        name: "ControllerActionApi",
        routeTemplate: "api/{controller}/{action}"
    );
    //
    config.Routes.MapHttpRoute(
        name: "ControllerApi",
        routeTemplate: "api/{controller}"
    );

这篇关于ASP NET的Web API路线模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆