405 HTTP Status Code in ASP.NET Core Web API

405 HTTP Status Code in ASP.NET Core Web API

In this article, I will discuss How to Return the 405 Method Not Allowed HTTP Status Code in ASP.NET Core Web API Application with Examples. Please read our previous article discussing How to Return the 404 Not Found HTTP Status Code in ASP.NET Core Web API with Examples.

405 HTTP Status Code

The 405 HTTP status code is defined as “Method Not Allowed.” This response is sent by a server when it recognizes the request method (e.g., GET, POST, DELETE, PUT, etc.), but the method is not supported or allowed for the requested resource. It indicates that the web server has understood the request but refuses to authorize the requested method.

When a server returns a 405 Status Code, it should also include an Allow header to inform the client of the allowed methods for the requested resource. For example, if a client sends a PUT request to a resource that only supports GET and POST, the server might respond with a 405 Status Code and include an Allow: GET POST header in the response.

The 405 Status Code is part of the HTTP/1.1 standard, as defined by the Internet Engineering Task Force (IETF) in RFC 7231. It is important for web developers and server administrators to handle this status code properly, ensuring that clients receive clear and useful feedback about allowed methods for resources, which can assist in debugging and application development.

How to Return 405 HTTP Status Code in ASP.NET Core Web API

The 405 Status Code is typically used when the server understands the request method, but the method has been disabled and cannot be used for the requested resource. To return a 405 HTTP status code in an ASP.NET Core Web API, indicating that the requested HTTP method is not allowed for the targeted resource, you can follow the below steps.

Attribute Routing and HTTP Method Attributes

ASP.NET Core uses Attribute Routing to map requests to controller actions. Along with routing, you can specify the HTTP methods that an action supports using specific HTTP method attributes like [HttpGet], [HttpPost], [HttpPut], [HttpDelete], etc. If a request is made using a method not supported by the action, ASP.NET Core automatically returns a 405 Status Code. Ensure your controller action is correctly decorated with the appropriate HTTP method attribute:

using Microsoft.AspNetCore.Mvc;

namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SampleController : ControllerBase
    {
        // This action only supports POST method
        [HttpPost]
        public IActionResult PostAction()
        {
            return Ok("Data processed");
        }
    }
}

Now, if you access the above method using the HTTP GET, PUT, or DELETE request, it will give you a 405 Method Not Allowed status code, as shown in the image below. Here, I am using the Postman and GET methods to access the above API.

How to Return 405 HTTP Status Code in ASP.NET Core Web API

Now, if you verify the Response header, then you will see that it must include the Allow header and set its value to Post as shown in the below image. This tells the client that please use a POST request to access the above endpoint.

405 HTTP Status Code in ASP.NET Core Web API

Missing HTTP Method Attribute in ASP.NET Core Web API

If an action method in a controller lacks a specific HTTP method attribute (e.g., [HttpGet], [HttpPost]), and a request is made to that action using a method that ASP.NET Core does not assume by convention, the framework might return a 405 Status Code if it cannot unambiguously determine the intended method.

Let us understand this with an example. Please modify the SampleController as follows. As you can see below, we have not decorated the action method with any HTTP Verb Attribute. But within the action method, we have handled the 405 Method Not Allowed Scenario explicitly. If the request method type is POST or PUT, the request is going to be handled by the server. Other than POST and PUT, we are explicitly returning the 405 Method Not Allowed status code.

using Microsoft.AspNetCore.Mvc;
namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    public class SampleController : ControllerBase
    {
        public IActionResult UnifiedMethod()
        {
            if (HttpContext.Request.Method == HttpMethod.Post.Method)
            {
                return Ok("Handled POST request");
            }
            else if (HttpContext.Request.Method == HttpMethod.Put.Method)
            {
                return Ok("Handled PUT request");
            }
            else
            {
                var customResponse = new
                {
                    Code = 405,
                    Message = "Support Method are POST and PUT"
                };
                // Explicitly return 405 for Unsupported Methods
                return StatusCode(StatusCodes.Status405MethodNotAllowed, customResponse);
            }
        }
    }
}

Now, run the application and try to access the action method with a GET request, and you should see the following response body:

Missing HTTP Method Attribute in ASP.NET Core Web API

Custom Middleware for Handling 405 Method Not Allowed in ASP.NET Core Web API

If you need more control over the response or wish to provide additional information in the body of the 405 Response, you can create custom middleware. So, create a class file named MethodNotAllowedMiddleware.cs and then copy and paste the following code:

using System.Net;
using System.Text.Json;

namespace ReturnTypeAndStatusCodes.Models
{
    public class MethodNotAllowedMiddleware
    {
        private readonly RequestDelegate _next;

        public MethodNotAllowedMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            await _next(context);
            if (context.Response.StatusCode == (int)HttpStatusCode.MethodNotAllowed)
            {
                context.Response.ContentType = "application/json";
                var customResponse = new
                {
                    Code = 405,
                    Message = "HTTP Method not allowed"
                };
                var responseJson = JsonSerializer.Serialize(customResponse);
                await context.Response.WriteAsync(responseJson);
            }
        }
    }
}
In the above example,
  • RequestDelegate _next: A function delegate that represents the next middleware in the pipeline. ASP.NET Core middleware components are connected in a chain, where each component can decide whether to pass the HTTP context object to the next component.
  • Constructor: The constructor takes a RequestDelegate named next as a parameter, which represents the next middleware in the request pipeline. This delegate is stored in a private field for later use.
  • Invoke: This is the method called by the ASP.NET Core runtime to execute the middleware. It takes an HttpContext object as a parameter, which provides information about the current HTTP request and response. The method is asynchronous, indicated by the async keyword and the return type of Task. This allows for asynchronous operations within the middleware, such as reading from or writing to the response.
  • await _next(context): This line calls the next middleware in the pipeline, passing along the HttpContext. This is important as it allows the request to flow through the remaining middleware components, including reaching the eventual endpoint that processes the request.
  • After calling the next middleware, the code checks if the response status code is 405 (HttpStatusCode.MethodNotAllowed). If the status code is 405, it sets the response’s ContentType to application/json. This is important for informing the client that the response body is in JSON format.
  • It then writes a JSON string to the response body with a custom error message indicating that the HTTP method used in the request is not allowed. This is done using context.Response.WriteAsync(…), which asynchronously writes the specified data to the HTTP response body.
Register the Custom Middleware to the Request Processing Pipeline:

After creating the middleware, you need to register it in the Program class. It’s important to add it at the right point in the middleware pipeline to ensure that it catches 405 responses correctly.

app.UseMiddleware<MethodNotAllowedMiddleware>();

This middleware checks the status code after all other middleware has been executed. If the status code is 405, it modifies the response to include a custom JSON message indicating that the HTTP Method is Not Allowed.

Modifying the Sample Controller as follows:
using Microsoft.AspNetCore.Mvc;

namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SampleController : ControllerBase
    {
        // This action only supports POST method
        [HttpPost]
        public IActionResult PostAction()
        {
            return Ok("Data processed");
        }
    }
}

Now, run the application and access the api/sample endpoint using other than the Post method, and you should get the following response:

Custom Middleware for Handling 405 Method Not Allowed in ASP.NET Core Web API

In the next article, I will discuss How to Configure the Allowed HTTP Methods Globally in ASP.NET Core Web API with Examples. In this article, I try to explain How to Return 405 Method Not Allowed HTTP Status Code in ASP.NET Core Web API with Examples, and I hope you enjoy this article on “405 Method Not Allowed HTTP Status Code in the ASP.NET Core Web API”.

Leave a Reply

Your email address will not be published. Required fields are marked *