2

We have a requirement of disabling the HTTP methods besides POST, GET and Head in an ASPNET Core Web application due as a part of security fixes. How can we disable the HTTP OPTIONS method in ASP.Net core API? Allowed 3 methods which are POST,GET and Head. How to block all the others method which I didn't use in middleware like DELETE,TRACE,PATCH and etc. Needs to return Error Code 405 = Method Not Allowed . Currently it throws the error 500 which is Internal Server Error

my code right now .

 app.Use(async (context, next) =>
            {
                if (context.Request.Method=="TRACE")
                {
                    context.Response.StatusCode = 405;
                    return; 
                }
                await next.Invoke();
            });

How to Block Http Methods in ASP.NET

Suzaku
  • 21
  • 3
  • Seems like you want an allow list instead of a deny list. Only accept requests that are POST, GET and HEAD. What you have looks fine. – davidfowl Dec 16 '22 at 07:14

1 Answers1

2

You could try as below:

app.MapWhen(x => x.Request.Method == "somemethod",
                y => y.Use(async(context,next)=>
                {
                    context.Response.StatusCode = 405;
                    await context.Response.WriteAsync("Method Not Allowed");
                }
            ));

The Result:

enter image description here

Ruikai Feng
  • 6,823
  • 1
  • 2
  • 11