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

夙愿已清 提交于 2020-01-13 10:29:08

问题


I'm overriding ASP.NET MVC's Controller.HandleUnknownAction(string actionName) method. It's being called when an action is not found and also when an HTTP method is not allowed. How can I distinguish between the two? I'd like to return a 404 when and action is not found and 405 when a method is note allowed.


回答1:


The simplest way I can think of is to create custom action filter. This will allow you to return http status code result if 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 more generic version of it, much 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();
}

Customizing attribute to take HttpVerbs as parameter is up to you.



来源:https://stackoverflow.com/questions/10386347/asp-net-mvc-controller-handleunknownaction-404-or-405

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!