【问题标题】:Basic Conventional routing asp.net webapi基本常规路由 asp.net webapi
【发布时间】:2017-08-20 04:04:23
【问题描述】:

我有一个关于 ASP.Net Web API 路由的简单查询。我有以下控制器:

public class CustomersController: ApiController
{
    public List<SomeClass> Get(string searchTerm)
    {
         if(String.IsNullOrEmpty(searchTerm))
         {
             //return complete List
         }
         else
         {
             //return list.where (Customer name contains searchTerm)
         }
    }
}

我的路由配置(常规)如下所示:

config.Routes.MapHttpRoute(name:"DefaultApi",
routeTemplate:"api/{controller}/{id}"
defaults:new {id = RouteParameter.Optional});

config.Routes.MapHttpRoute(name:"CustomersApi",
routeTemplate:"api/{controller}/{searchTerm}"
defaults:new {searchTerm = RouteParameter.Optional});

如果我点击网址: http://localhost:57169/api/Customers/Vi 我收到 404-未找到

如果我颠倒路线的顺序,它会起作用。 所以问题是在第一种情况下,它是否匹配第一个路由(DefaultApi)?如果不是,为什么不尝试第二条路线?

【问题讨论】:

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


    【解决方案1】:

    此路线模板

    config.Routes.MapHttpRoute(name:"DefaultApi",
        routeTemplate:"api/{controller}/{id}",
        defaults:new {id = RouteParameter.Optional}
    );
    

    匹配您的 URL,因为 Id 可以是任何类型:string、int 等。因此您的 URL 尊重此模板并选择此路由。

    要使这个模板更具限制性并使 ASP.Net Web API 转到下一个模板,您需要通过说“Id 参数必须是这个模板的数字类型来添加一些约束。 ”。所以你添加constraints 参数如下:

    config.Routes.MapHttpRoute(name:"DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new {id = RouteParameter.Required}, // <- also here I put Required to make sure that when your user doesn't give searchTerm so this template will not be chosen.
        constraints: new {id = @"\d+"} // <- regular expression is used to say that id must be numeric value for this template.
    );
    

    因此,通过使用此 URL http://localhost:57169/api/Customers/Vi,将跳过上述模板并选择下一个。

    【讨论】:

    • 如果选择了这个路由,那为什么不触发Controller方法呢?是不是因为Controller方法中的参数名是searchTerm而不是id?
    • 它选择了,但客户控制器中没有将“id”作为参数的操作。当未找到操作时,它返回 404。ASP.Net Web API 不会再次返回到您的模板列表中以采用另一个路由模板。
    • 所以你的意思是,路由解析不考虑参数名。首先选择路由,然后匹配参数。对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多