简体   繁体   中英

ASP.NET override '405 method not allowed' http response

In ASP.NET WebAPI I have a controller/action which is accessible by using the GET verb. If I query the endpoint using POST verb I get a standard 405 method not allowed response.

Is is possible to intercept this behaviour and inject my own custom response instead of that one without adding code to the controllers? Or maybe somehow overwrite the original response. This behavior is expected to be present application wide, so I will somehow have to set this setting globally.

This behavior of a 405 is determined by the pipeline looking for a proper controller, then a proper method by either naming convention or attributes. I see two ways for you to achieve your desired result, a custom IHttpActionSelector or a base ApiController.

Example code for IHttpActionSelector:

public class CustomHttpActionSelector : IHttpActionSelector
{
    public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
    {
        var isPostSupported = false;

        //logic to determine if you support the method or not

        if (!isPostSupported)
        {
            //set any StatusCode and message here
            var response = controllerContext.Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, "Overriding 405 here.");
            throw new HttpResponseException(response);
        }
    }

    ...
}

//add it to your HttpConfiguration (WebApiConfig.cs)
config.Services.Add(typeof(IHttpActionSelector), new CustomHttpActionSelector());

Example code for a base ApiController:

public abstract class BaseApiController<T> : ApiController
{
    public virtual IHttpActionResult Post(T model)
    {
        //custom logic here for "overriding" the 405 response
        return this.BadRequest();
    }
}

public class UsersController : BaseApiController<User>
{
    public override IHttpActionResult(User model)
    {
        //do your real post here
        return this.Ok();
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM