小编典典

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

c#

我正在将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如下所示

  • 列出Get()= api/customers/
  • 客户GetCustomerById(字符串ID)= api/customers/13
  • 列表GetCustomerByCurrentMonth()= /customers/currentMonth
  • 客户GetCustomerByUsername(字符串用户名)= /customers/customerByUsername/yasser

我尝试对路由进行更改,但是由于不熟悉它,我对此不太了解。

因此,请有人可以帮助我了解并指导我如何进行。谢谢


阅读 362

收藏
2020-05-19

共1个答案

小编典典

从这里开始在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" }
        );
    }
}
2020-05-19