在ASP.NET Web API中使用多个Get方法进行路由 [英] Routing with multiple Get methods in ASP.NET Web API
问题描述
我正在将Web Api与ASP.NET MVC一起使用,对此我很陌生.我已经在asp.net网站上进行了一些演示,我正在尝试执行以下操作.
I am using Web Api with ASP.NET MVC, and I am very new to it. I have gone through some demo on asp.net website and I am trying to do the following.
我有4种get方法,具有以下签名
I have 4 get methods, with the following signatures
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如下所示
For all the methods above I would like to have my web api somewhat like as shown below
- 列表Get()=
api/customers/
- 客户GetCustomerById(字符串ID)=
api/customers/13
- 列表GetCustomerByCurrentMonth()=
/customers/currentMonth
- 客户GetCustomerByUsername(字符串用户名)=
/customers/customerByUsername/yasser
- List Get() =
api/customers/
- Customer GetCustomerById(string Id) =
api/customers/13
- List GetCustomerByCurrentMonth() =
/customers/currentMonth
- Customer GetCustomerByUsername(string username) =
/customers/customerByUsername/yasser
我尝试对路由进行更改,但是由于我是新手,所以不太了解.
I tried making changes to routing, but as I am new to it, could'nt understand much.
因此,请有人可以帮助我了解并指导我该如何进行.谢谢
So, please can some one help me understand and guide me on how this should be done. Thanks
推荐答案
从此处 Darin Dimitrov 发布了一个很好的答案,这对我有用.
Darin Dimitrov has posted a very good answer which is working for me.
它说...
您可能有两条路线:
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" }
);
}
}
这篇关于在ASP.NET Web API中使用多个Get方法进行路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!