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

标签 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
}

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

  • List Get() = api/customers/
  • 客户 GetCustomerById(string Id) = api/customers/13
  • List GetCustomerByCurrentMonth() = /customers/currentMonth
  • Customer GetCustomerByUsername(字符串用户名) = /customers/customerByUsername/yasser

我尝试更改路由,但由于我是新手,所以不太了解。

所以,请有人帮助我理解并指导我应该如何完成这项工作。谢谢

最佳答案

从这里Routing in Asp.net Mvc 4 and 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" }
        );
    }
}

关于c# - 在 ASP.NET Web API 中使用多个 Get 方法进行路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12775590/

相关文章:

c# - C# 一次性变量的自一次性(内联)声明

asp.net-mvc - 有没有办法为每个 Controller 方法添加虚拟方法行为? (即记录)

Asp.net Web API : No action was found on the controller

c# - Entity Framework 获取单个项目真的很慢

c# - ASP.NET 网络 API : Optional Guid parameters

c# - WebApi—— Controller 继承——方法的新版本

c# - Controller 中操作的路径模板不是有效的 OData 路径模板

c# - 如何将 Expression<Func<BaseClass, bool>> 转换为 Expression<Func<InheritedClass, bool>>?

c# - Entity Framework 4(纯 POCO)上的更新操作问题

c# - Microsoft.Build.BuildEngine 可以是多线程的吗