基本常规路由 asp.net webapi
Basic Conventional routing asp.net webapi
我在 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});
如果我点击 url:
http://localhost:57169/api/Customers/Vi
我收到 404-Not found
如果我颠倒路线的顺序,就可以了。
所以问题是第一种情况,是否匹配第一个路由(DefaultApi)?如果不是,为什么不尝试第二条路线?
此路线模板
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 上面的模板将被跳过并选择下一个。
我在 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});
如果我点击 url: http://localhost:57169/api/Customers/Vi 我收到 404-Not found
如果我颠倒路线的顺序,就可以了。 所以问题是第一种情况,是否匹配第一个路由(DefaultApi)?如果不是,为什么不尝试第二条路线?
此路线模板
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 上面的模板将被跳过并选择下一个。