Web 中的方法名称约定 API 2

Method name conventions in Web API 2

是否有 Web API2 中使用的约定的列表?

以这两种方式为例。两者都有效,都没有用属性装饰。

IHttpActionResult GetMyModel(int id)

IEnumerable<MyModel> GetAllMyModels()

Get 响应路由“{controller}/{action}/{id}”,所以我假设 GetAllMyModels 有效是因为它的 return 类型?或者 GetAll 前缀?

还有其他约定吗?

在相关说明中,为什么 GetAllMyModels return 是可枚举的,而 GetMyModel return 是 IHttpActionResult 中的 MyModel?我应该从 GetAllMyModels returned IHttpActionResult 吗?

因此,扩展它似乎只是 return 某种元素集合的约定。您可以愉快地 return 单个元素,它只映射参数,在本例中为 0.

对于 GetAllMyModels 案例,我尝试了各种替代方案并解决了以下问题。

GetAllMyModels - 是
GetMyModels - 是
我的模型 - 否
GetHorses - 是

所以答案似乎是,如果签名以 Get 开头并且签名 return 是一个 IEnumerable* 并且 EntityType 与其他控制器方法上使用的类型相匹配并且它没有参数那么它是用作return所有实体的方法。

*我的情况 return 类型是可枚举的而不是 IHttpActionResult 是 shorthand。它等效于 return 类型的 IHttpActionResult 和 returning Ok(值)。

如果方法的名称以定义的 HTTP 方法开头,则在没有特定属性定义的情况下它将映射到该方法。

private static Collection<HttpMethod> GetSupportedHttpMethods()

System.Web.Http.Controllers.ReflectedHttpActionDescriptor 使用 _supportedHttpMethodsByConvention

private static readonly HttpMethod[] _supportedHttpMethodsByConvention = 
{ 
    HttpMethod.Get, 
    HttpMethod.Post, 
    HttpMethod.Put, 
    HttpMethod.Delete, 
    HttpMethod.Head, 
    HttpMethod.Options, 
    new HttpMethod("PATCH") 
};

<截图/>

// Get HttpMethod from method name convention 
for (int i = 0; i < _supportedHttpMethodsByConvention.Length; i++)
{
    if (methodInfo.Name.StartsWith(
        _supportedHttpMethodsByConvention[i].Method, 
        StringComparison.OrdinalIgnoreCase))
    {
        supportedHttpMethods.Add(_supportedHttpMethodsByConvention[i]);
        break;
    }
}

请注意,如果未定义其他内容,则 POST 是默认的 HTTP 方法。

您可以通过浏览 Web API 2 source code.

来了解发生了什么