ASP.NET MVC: Controller.HandleUnknownAction 404 or 405?

I override the ASP.NET MVC Controller.HandleUnknownAction (string actionName) method. It is called when an action is not found, and also when the HTTP method is not allowed. How can I distinguish between the two? I would like to return 404 when both the action is not found and 405 when the method is allowed.

+5
source share
1 answer

The easiest way I can come up with is to create a custom action filter. This will allow you to return the result of the http status code if the method is not allowed.

public class HttpPostFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!(filterContext.RequestContext.HttpContext.Request.GetHttpMethodOverride().Equals("post", StringComparison.InvariantCultureIgnoreCase)))
        {
            filterContext.Result = new HttpStatusCodeResult(405);
        }
    }
}

Or better, create a more general version, like AcceptVerbsAttribute

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class AllowMethodsAttribute : ActionFilterAttribute
{
    public ICollection<string> Methods
    {
        get;
        private set;
    }

    public AllowMethodsAttribute(params string[] methods)
    {
        this.Methods = new ReadOnlyCollection<string>(methods);
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride();
        if (!this.Methods.Contains(httpMethodOverride, StringComparer.InvariantCultureIgnoreCase))
        {
            filterContext.Result = new HttpStatusCodeResult(405);
        }
    }
}

And use it like

[AllowMethods("GET")]
public ActionResult Index()
{
    ViewBag.Message = "Welcome to ASP.NET MVC!";

    return View();
}

HttpVerbs, .

+3

All Articles