Hi @Jain, Akshitha,
Here are the multiple ways to disabling specific HTTP methods for an Azure-hosted .NET MVC application:
1)You can handle the Application_BeginRequest
event in the Global.asax file to check for the HTTP method and terminate requests that use methods you want to disable.
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.HttpMethod == "OPTIONS" || Request.HttpMethod == "TRACE" /* ... other methods ... */)
{
Response.StatusCode = 403; // Forbidden
Response.End();
}
}
2)If you are using ASP.NET Core, you can implement middleware to check for the HTTP method and short-circuit the pipeline if it matches one of the methods you wish to block.
3)You can create a custom action filter to reject requests with unwanted HTTP methods.
public class BlockHttpMethodsAttribute : ActionFilterAttribute
{
private readonly string[] _methods;
public BlockHttpMethodsAttribute(params string[] methods)
{
_methods = methods;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (_methods.Contains(filterContext.HttpContext.Request.HttpMethod, StringComparer.OrdinalIgnoreCase))
{
filterContext.Result = new HttpStatusCodeResult(405); // Method Not Allowed
}
}
}
You can then apply this filter globally or to specific controllers/actions in your application.
Best regards,
Jalpa Panchal
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.