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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With