WebAPI 2. Respond to all HTTP verbs with the same controller method

I want to answer all Http verbs with the same controller method. The only way I have found is to decorate a method that will use all http methods. It seems to me that there must be a better way. Will one decoration be better or can only one route definition be defined?

[HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPost, HttpPatch, HttpPut]

+3


source to share


2 answers


You can decorate your controller method using the AcceptVerbs attribute like this.



[AcceptVerbs("PATCH", "GET", "DELETE")]

      

+2


source


I think you can achieve your goal, customize your routing to something like an example:

routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "all", id = RouteParameter.Optional }

      

);



Note that the entire method will always be called inside your controllers.

Also, there might be a better approach depending on your needs, for example if you only have one controller to be the only entry point, or if you might have special inputs in your urls. Note that you will have to deal with mail and fetch data inside your controller method, which may not be ideal as I said it would depend on your specifications.

There is another way to solve the problem of routing or controller and method selection that might help you, you can implement your own IHttpControllerSelector.SelectController to manage controller selection or IHttpActionSelector.SelectAction to handle method selection, have a look at Web Api 2 Documentation.

+1


source







All Articles