2

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?

Friso
  • 2,328
  • 9
  • 36
  • 72

1 Answers1

3

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.

Yared
  • 2,206
  • 1
  • 21
  • 30
  • Thanks @Yared. My only suggestion is to change it from VerbsToExclude to VerbsToInclude and reverse the if statement. That way you specify the ones you know you handle, and everything else is blocked – IeuanW Aug 10 '20 at 16:27
  • how to exclude verbs on appsetting.json file ? – Saad Awan Nov 11 '20 at 08:37