Original: Routing in ASP Web API
When we create a new Web API project, a default route is defined in WebApiConfig.cs under the app_start folder:
CONFIG. Routes.maphttproute ( "defaultapi", "api/{ Controller}/{id}", new {id = routeparameter.optional} );
The "API" is added to the default route to avoid routing conflicts with ASP. Of course, if you don't like the convention, you can modify the default route.
Route matching rule: {controller} and {ID} skipped, only description of action match.
The 1.WEB API first looks for an action named for the HTTP method name that starts with the HTTP method name. Example:
Public class productscontroller:apicontroller{ publicvoid getallproducts () {} Public Ienumerable<product> Getproductbyid (int ID) {} public Httpresponsemessage deleteproduct (int ID) {}}
2. However, the above conventions apply only to get, POST, put, and delete methods. The other HTTP methods can be matched using Acceptverbs attribute, and the previous four methods also apply. Example:
public class productscontroller:apicontroller{[HttpGet] p Ublic Product findproduct (ID) {}}
public class productscontroller:apicontroller{[Acceptverbs ( " get , " head )] Product findproduct (id) {} // WebDAV method [Acceptverbs ( " Span style= "color: #800000;" >mkcol )] public void Makecollection () {}}
3. Match by Action name (rewrite route). Example:
routes. Maphttproute ( "actionapi", "api/{controller}/{ Action}/{id}", new {id = routeparameter.optional});
3.1. The GET request according to the above routing rule "api/products/details/1" will match:
Public class productscontroller:apicontroller{ [httpget] publicstring Details (int ID);}
3.2. You can use ActionName attribute to override the action name. Example:
Public class productscontroller:apicontroller{ [HttpGet] [ActionName ("Thumbnail" )] public httpresponsemessage getthumbnailimage (int ID); [HttpPost] [ActionName ("Thumbnail")] Public void Addthumbnailimage (int ID);}
This "api/products/thumbnail/ID" has two matches, corresponding to get and post respectively.
4. If a method does not want to be invoked as an action, you can use Nonaction attribute, for example:
// Not an action method. [nonaction] Public string GetPrivateData () {...}
Translation routing of ASP. NET Web API