5

Tôi đang ghi đè phương thức Controller.HandleUnknownAction (chuỗi actionName) của ASP.NET MVC. Nó được gọi khi một hành động không được tìm thấy và cũng có thể khi một phương thức HTTP không được phép. Làm thế nào tôi có thể phân biệt giữa hai? Tôi muốn trả lại 404 khi không tìm thấy hành động và 405 khi một phương thức được cho phép.ASP.NET MVC: Controller.HandleUnknownAction 404 hoặc 405?

Trả lời

3

Cách đơn giản nhất tôi có thể nghĩ là tạo bộ lọc tác vụ tùy chỉnh. Điều này sẽ cho phép bạn trả về kết quả mã trạng thái http nếu phương pháp không được phép

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

Hoặc tốt hơn, tạo ra phiên bản chung chung hơn của nó, giống như 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); 
     } 
    } 
} 

Và sử dụng nó như

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

    return View(); 
} 

Tùy chỉnh thuộc tính để thực hiện HttpVerbs làm thông số tùy thuộc vào bạn.

Các vấn đề liên quan