5

我正在覆盖 ASP.NET MVC 的 Controller.HandleUnknownAction(string actionName) 方法。当未找到操作以及不允许使用 HTTP 方法时,将调用它。我怎样才能区分这两者?我想在未找到操作时返回 404,在允许方法时返回 405。

4

1 回答 1

4

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

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作为参数由您决定。

于 2012-04-30T16:38:03.300 回答