问题
Is there a list of what conventions are used in Web API 2?
Take these two methods for example. Both work, neither are decorated with attributes.
IHttpActionResult GetMyModel(int id)
IEnumerable<MyModel> GetAllMyModels()
Get
responds to the route "{controller}/{action}/{id}", so I assume GetAllMyModels
works because of its return type? Or the GetAll
prefix?
Are there other conventions?
On a related note, why does GetAllMyModels
return an enumerable while GetMyModel
returns the MyModel
in the IHttpActionResult
? Should I have returned IHttpActionResult
from GetAllMyModels
?
Thanks
回答1:
If the name of a method starts with a defined HTTP Method it will be mapped to that method in the absence of a specific attribute definition.
private static Collection<HttpMethod> GetSupportedHttpMethods()
in System.Web.Http.Controllers.ReflectedHttpActionDescriptor
uses _supportedHttpMethodsByConvention
private static readonly HttpMethod[] _supportedHttpMethodsByConvention =
{
HttpMethod.Get,
HttpMethod.Post,
HttpMethod.Put,
HttpMethod.Delete,
HttpMethod.Head,
HttpMethod.Options,
new HttpMethod("PATCH")
};
<snip/>
// 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;
}
}
Note that POST is the default HTTP Method if nothing else is defined.
You can work out what is going on by browsing through the Web API 2 source code.
回答2:
So to expand it seems it's just a convention to return some sort of collection of elements. You can just as happily return a single element, it just maps the parameters, in this case 0.
For the GetAllMyModels case I tried various alternatives and it resolves the following.
GetAllMyModels - Yes GetMyModels - Yes MyModels - No GetHorses - Yes
So the answer appears to be that if the signature starts with Get and has a signature that returns an IEnumerable* and EntityType matches the type used on other controller methods AND it has no parameters then it is used as the method that returns all entities.
*My side case where the return type is an enumerable instead of IHttpActionResult is shorthand. It is equivalent to a return type of IHttpActionResult and returning Ok(the values).
来源:https://stackoverflow.com/questions/35340205/method-name-conventions-in-web-api-2