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

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

问题描述

我正在重写 ASP.NET MVC 的 Controller.HandleUnknownAction(string 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 状态代码结果

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

然后像这样使用

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

    return View();
}

自定义属性以将 HttpVerbs 作为参数由你决定.

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

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

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