gpt4 book ai didi

asp.net-mvc - ASP.NET MVC : Controller. HandleUnknownAction 404 或 405?

转载 作者:行者123 更新时间:2023-12-02 08:03:04 25 4
gpt4 key购买 nike

我正在重写 ASP.NET MVC 的 Controller.HandleUnknownAction(string actionName) 方法。当未找到操作以及不允许使用 HTTP 方法时,就会调用它。我如何区分两者?我想在未找到操作时返回 404,在允许注释方法时返回 405。

最佳答案

我能想到的最简单的方法是创建自定义操作过滤器。如果方法不允许,这将允许您返回 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因为参数取决于你。

关于asp.net-mvc - ASP.NET MVC : Controller. HandleUnknownAction 404 或 405?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10386347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com