在ASP.NET Web API中使用多个Get方法进行路由

Yas*_*ser 60 c# asp.net-web-api asp.net-web-api-routing

我正在使用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
}
Run Code Online (Sandbox Code Playgroud)

对于上面的所有方法,我希望我的web api有点像下面所示

  • 列表Get()= api/customers/
  • Customer GetCustomerById(string Id)= api/customers/13
  • 列出GetCustomerByCurrentMonth()= /customers/currentMonth
  • Customer GetCustomerByUsername(string username)= /customers/customerByUsername/yasser

我尝试对路由进行更改,但由于我是新手,因此无法理解.

所以,请一些人帮助我理解并指导我如何做到这一点.谢谢

Yas*_*ser 74

从这里路由Asp.net Mvc 4和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" }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)


cuo*_*gle 47

首先,添加带有操作的新路线:

  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 }
        );
Run Code Online (Sandbox Code Playgroud)

然后使用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
}
Run Code Online (Sandbox Code Playgroud)

  • 这在纸面上看起来不错,但实际上并不起作用.你必须做这个帖子的第二个答案:http://stackoverflow.com/questions/9569270/custom-method-names-in-asp-net-web-api诀窍是在id上添加一个int约束第一个路径中的参数,并将默认操作设置为"获取"以及第二个路径上的HttpGet约束 (7认同)

Lal*_*iya 16

您还将为设置路线指定行动路线

[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
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为这个答案很简单,直接与.NET Core兼容.但是可以避免重复的路由前缀.请参阅:/sf/ask/894291331/#49070866 (5认同)

Maj*_*jor 11

这个问题已经有很多很好的答案了。然而,现在路由配置有点“不推荐”。较新版本的 MVC (.NET Core) 不支持它。所以最好习惯它:)

所以我同意所有使用属性样式路由的答案。但我一直注意到每个人都重复了路线的基本部分(api/...)。最好在 Controller 类的顶部应用[RoutePrefix]属性,并且不要一遍又一遍地重复相同的字符串。

[RoutePrefix("api/customers")]
public class MyController : Controller
{
 [HttpGet]
 public List<Customer> Get()
 {
   //gets all customer logic
 }

 [HttpGet]
 [Route("currentMonth")]
 public List<Customer> GetCustomerByCurrentMonth()
 {
     //gets some customer 
 }

 [HttpGet]
 [Route("{id}")]
 public Customer GetCustomerById(string id)
 {
  //gets a single customer by specified id
 }
 [HttpGet]
 [Route("customerByUsername/{username}")]
 public Customer GetCustomerByUsername(string username)
 {
    //gets customer by its username
 }
}
Run Code Online (Sandbox Code Playgroud)


Pal*_*mar 5

只有一条路线足够了

config.Routes.MapHttpRoute("DefaultApiWithAction", "{controller}/{action}");
Run Code Online (Sandbox Code Playgroud)

并且需要在所有操作中指定属性HttpGetHttpPost.

[HttpGet]
public IEnumerable<object> TestGet1()
{
    return new string[] { "value1", "value2" };
}

[HttpGet]
public IEnumerable<object> TestGet2()
{
    return new string[] { "value3", "value4" };
}
Run Code Online (Sandbox Code Playgroud)