I have an action on an ApiController
in an ASP.NET project.
I want it to accept any HTTP method (even bogus ones, if possible).
I can't find a Don't filter by method attribute though. Do I have to create one?
Adding multiple attributes works fine for the standard methods. Can I catch everything though?
NB This is a Framework 4.72 application, not a Core application
You cannot ignore filtering by HTTP
method completely in Web API
, the framework seems to be pretty strict in this matter. But you can specify predefined set of any method names you need (even bogus ones) using AcceptVerbs
attribute
[AcceptVerbs("POST", "GET", "MyMethod", "Bo-Gus")]
public IHttpActionResult MyAction()
Or you can implement IActionHttpMethodProvider
that returns allowed methods
[AttributeUsage(AttributeTargets.Method)]
public class AllowBogusMethodsAttribute : Attribute, IActionHttpMethodProvider
{
public Collection<HttpMethod> HttpMethods
{
get
{
return new Collection<HttpMethod>
{
HttpMethod.Get,
HttpMethod.Post,
new HttpMethod("MyMethod"),
new HttpMethod("Bo-Gus")
};
}
}
}
and use it like this
[AllowBogusMethods]
public IHttpActionResult MyAction()
Note
HttpMethods
getter will be called only once during application lifetime and its result will be cached, and therefore you cannot add new allowed HTTP
methods during requests and return updated collection.
If you do not apply any action verb, then that action will be treated as GET
request action. That is the default behavior.
I never tried with adding HttpGet, HttpPost
, Put
etc. to the same action.
Alternative approach would be to have individual actions for different http verbs and then redirect to one action with parameters.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.