Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept any HTTP method/verb in ASP.NET WebAPI

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

like image 419
BanksySan Avatar asked May 31 '26 01:05

BanksySan


1 Answers

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.

like image 65
Alexander Avatar answered Jun 02 '26 15:06

Alexander