我正在将 Web Api 与 ASP.NET MVC 结合使用,我对它还很陌生。我已经在 asp.net 网站上进行了一些演示,我正在尝试执行以下操作。
我有 4 个 get 方法,具有以下签名
public List<Customer> Get()
{
// gets all customer
}
public List<Customer> GetCustomerByCurrentMonth()
{
// gets some customer on some logic
}
public Customer GetCustomerById(string id)
{
// gets a single customer using id
}
public Customer GetCustomerByUsername(string username)
{
// gets a single customer using username
}
对于上面的所有方法,我希望我的 web api 有点像下面所示
- List Get() =
api/customers/
- 客户 GetCustomerById(string Id) =
api/customers/13
- List GetCustomerByCurrentMonth() =
/customers/currentMonth
- Customer GetCustomerByUsername(字符串用户名) =
/customers/customerByUsername/yasser
我尝试更改路由,但由于我是新手,所以不太了解。
所以,请有人帮助我理解并指导我应该如何完成这项工作。谢谢
最佳答案
从这里Routing in Asp.net Mvc 4 and Web Api
Darin Dimitrov 发布了一个对我有用的非常好的答案。
它说...
你可以有几条路线:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByName",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null,
constraints: new { name = @"^[a-z]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" }
);
}
}
关于c# - 在 ASP.NET Web API 中使用多个 Get 方法进行路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12775590/