5

我重寫ASP.NET MVC的Controller.HandleUnknownAction(string actionName)方法。當一個動作沒有被發現時,以及當一個HTTP方法不被允許時,它被調用。我如何區分這兩者?我想在沒有找到404的情況下返回404,並且在允許註釋方法時返回405。ASP.NET MVC:Controller.HandleUnknownAction 404或405?

回答

3

我能想到的最簡單的方法是創建自定義的行爲過濾器。這將允許您返回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作爲參數取決於您。