Search code examples
asp.netpostroutesasp.net-web-api2rpc

Web Api always accept POST verb on controller methods


With an action name routing such as:

config.Routes.MapHttpRoute(
    name: "ByActionName",
    routeTemplate: "api/{controller}/{action}");

I want that all my controller methods accept the POST verb, is there a way to configure the route map so that I don't need to put a HttpPost attribute to all controller methods?

I was hoping to do something like:

config.Routes.MapHttpRoute(
    name: "ByActionName",
    verb: "POST"
    routeTemplate: "api/{controller}/{action}");

Instead of:

public class MyController: ApiController
 {
     [HttpPost]
     public List<int> GetItems() { ... } 

     [HttpPost]
     public void DeleteItem(int id) { ... }

     [HttpPost]
     public void OtherMethod() { ... }
 }

Solution

  • If the method name begins with a verb such as Get,Delete, etc the default verb will match that. If the beginning of the method name doesn't match any verb, webapi defaults to HttpPost. So you can avoid putting [HttpPost] attributes by renaming your controller methods.

    See: Is there a default verb applied to a Web API ApiController method?