【问题标题】:Controller actions naming convention控制器动作命名约定
【发布时间】:2016-02-04 11:01:06
【问题描述】:

正如命名约定所说,WebApi 控制器操作名称应为 Get()、Put()。 Post() 等。但是告诉我,如果我有一个控制器作为 CustomerController,现在我想在其中有两个操作。一个是 GetCustomerById(int id),另一个是 GetCustomerByAge(int age)。这里两个动作都接受一个参数作为 int。

所以,如果我想让 url 像 "api/customer/" 一样对用户友好,我也想遵循操作命名约定,例如 Get(int id)/Get( int age),我该怎么做?

【问题讨论】:

  • 您使用的是哪个 Web Api 版本?如果您使用的是 Web Api 2,那么您可以使用 Route 属性。

标签: c# asp.net-web-api naming-conventions asp.net-web-api-routing


【解决方案1】:

Restful 服务不应在 URI 中包含 CRUD 函数名称 (https://restfulapi.net/resource-naming/)

这样会更合适:

对于 GetById - http://mysite/api/customers/123

对于 GetByAge - http://mysite/api/customers?age=21

【讨论】:

  • c# webservice方法中多态并不是那么容易。
【解决方案2】:

在这种情况下,严格遵守标准实际上可能对您没有多大帮助。

一种解决方案是让自己偏离 REST 风格。

你可以有两种获取方法:

一个可能是 GetByID,另一个可能是 GetByAge。

您的路线可能如下所示:

api/customer/getbyage/20 api/customer/getbyid/1134

这并不完全是 REST,但它足够接近,并且一个异常不会破坏任何东西。

我的观点是使用任何有助于您的产品有意义的实现,并且不要太担心标准。

【讨论】:

  • 您可以通过“/api/customers/1234”继续通过标识符指示实际资源来维护适当的 REST,同时使用“/api/customers?age=20”查找资源根据其他属性。
  • 我同意这个答案。有时约定很累。
【解决方案3】:

另一种方法是 HTTP 方法属性。

您可以通过使用 HttpGet、HttpPut、HttpPost 或 HttpDelete 属性装饰操作方法来显式指定操作的 HTTP 方法,而不是使用 HTTP 方法的命名约定。

在以下示例中,FindProduct 方法映射到 GET 请求:

public class ProductsController : ApiController
{
    [HttpGet]
    public Product FindProduct(id) {}
}

要允许一个操作使用多个 HTTP 方法,或允许 GET、PUT、POST 和 DELETE 以外的 HTTP 方法,请使用 AcceptVerbs 属性,该属性采用 HTTP 方法列表。

public class ProductsController : ApiController
{
    [AcceptVerbs("GET", "HEAD")]
    public Product FindProduct(id) { }
}

【讨论】:

    【解决方案4】:

    如果希望Web Api在路由时查找动作名称,请将App_Start文件夹中的WebApiConfig.cs类改成如下:

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    

    然后你可以发出一个GET请求

    http://mysite/api/customer/GetCustomerById/1
    

    另外我建议您阅读下面的文章以加深理解:

    Routing by Action Name

    【讨论】:

    猜你喜欢
    • 2020-11-14
    • 1970-01-01
    • 2012-04-24
    • 2020-09-06
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多