ASP.NET MVC:Controller.HandleUnknownAction 404或405? [英] ASP.NET MVC: Controller.HandleUnknownAction 404 or 405?

查看:527
本文介绍了ASP.NET MVC:Controller.HandleUnknownAction 404或405?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我重写ASP.NET MVC的Controller.HandleUnknownAction(字符串actionName)方法。当找不到一个动作它被称为,也当是不允许的HTTP方法。我如何区分这两个?我想返回404时和行动未发现和405时,音符允许的方法。

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.

推荐答案

我能想到的是创建自定义操作过滤器最简单的方法。这将允许您返回HTTP状态code的结果,如果方法是不允许的。

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);
        }
    }
}

或者更好,创造它更宽泛的版本,很像的 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);
        }
    }
}

和使用它像

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

    return View();
}

自定义属性采取 HttpVerbs作为参数是由你。

这篇关于ASP.NET MVC:Controller.HandleUnknownAction 404或405?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆