Search code examples
asp.net-coreweb-configasp.net-core-webapihttp-verbs

How do I exclude verbs in ASP.NET Core API?


I need to exclude verbs allowed for an API solution, but I can't find examples how to do it in web.config.

I did find an example for MVC that looks like this:

<configuration>
 <system.web>
  <httpHandlers>
   <remove verb="*" path="MyPage.aspx" type="MyHandler, MyAssembly"/>
   <add verb="*" path="MyPage.aspx" type="MySpecialHandler, MyAssembly"/>
  </httpHandlers>
 </system.web>
</configuration>

Is this how I should do it for an API as well?

If so, what should I put in the place of path?


Solution

  • In ASP.NET Core, implementation of HTTP handlers and modules are replaced by Middleware. This article has enough information how to migrate from HTTP handlers and modules to ASP.NET Core middleware. https://learn.microsoft.com/en-us/aspnet/core/migration/http-modules

    In order to achieve HTTP verbs exclusion from your API, you can write a simple middleware like this:

    public class VerbsMiddleware{
    
            private readonly RequestDelegate _next;
            private string[] VerbsToExclude = {"DELETE", "PUT"}; //You can put these in appsettings.json
    
            public VerbsMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task Invoke(HttpContext context){
    
                if (VerbsToExclude.Contains(context.Request.Method))
                {
                    context.Response.StatusCode = 405;
                    await context.Response.WriteAsync("Method Not Allowed");
                }
    
                await _next.Invoke(context);
            }
    
        }
    

    With the above middleware, you API returns status code of 405 for any HttpDelete and HttpPut requests.