0

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() { ... }
 }
Rafael
  • 2,642
  • 2
  • 24
  • 30

1 Answers1

2

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?

Sal
  • 5,129
  • 5
  • 27
  • 53
  • But it would be nice to have a way to tell the router to always allow e.g. POST verb although the method is named Get... in the case you're not developing a REST api but rather a more rpc-styled api. – Anttu Mar 24 '22 at 09:38
  • @Anttu No matter what you name your method you can always slap on a `[HttpPost]` attribute to allow POST operations. You could also create your own custom `Route` type to always allow POST operations. So you definitely have options and flexibility here. But you do need to decorate each method in your controller individually. – Sal Mar 24 '22 at 11:53
  • Yeah, I realized that when trying these things out in practice. I'd hope for a way to avoid having to bloat every action with that attribute and just set it in one place. I guess one can always do some reflection magic but would feel quite hacky. – Anttu Mar 30 '22 at 08:48