我正在使用Web和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如下所示
Get用户名列表Get() = api/customers/
api/customers/13
/customers/currentMonth
/customers/customerByUsername/yasser
我试着更改路由,但由于我是新手,无法理解太多。
所以,请有人能帮助我理解和指导我应该如何做。谢谢
发布于 2012-10-08 16:48:59
从这里开始Routing in Asp.net Mvc 4 and Web Api
发布了一个非常好的答案,对我来说很有效。
上面说..。
你可以有几条路由:
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" }
);
}
}
发布于 2012-10-08 13:43:53
首先,添加操作在顶部的新路由:
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
然后使用ActionName
属性来映射:
[HttpGet]
public List<Customer> Get()
{
//gets all customer
}
[ActionName("CurrentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
//gets some customer on some logic
}
[ActionName("customerById")]
public Customer GetCustomerById(string id)
{
//gets a single customer using id
}
[ActionName("customerByUsername")]
public Customer GetCustomerByUsername(string username)
{
//gets a single customer using username
}
发布于 2016-11-03 16:56:07
还可以指定用于设置路由的操作上的路由
[HttpGet]
[Route("api/customers/")]
public List<Customer> Get()
{
//gets all customer logic
}
[HttpGet]
[Route("api/customers/currentMonth")]
public List<Customer> GetCustomerByCurrentMonth()
{
//gets some customer
}
[HttpGet]
[Route("api/customers/{id}")]
public Customer GetCustomerById(string id)
{
//gets a single customer by specified id
}
[HttpGet]
[Route("api/customers/customerByUsername/{username}")]
public Customer GetCustomerByUsername(string username)
{
//gets customer by its username
}
https://stackoverflow.com/questions/12775590
复制相似问题