Reputation: 21
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
Upvotes: 2
Views: 1011
Reputation: 11711
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:
Upvotes: 2