在 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
- 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
推荐答案
从这里 Asp.net Mvc 4 和 Web Api 中的路由
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屋!