2009-07-02 82 views
3

我知道你可以通过添加AcceptVerbsAttribute来限制某个ActionResult方法响应的HTTP方法,例如,什么是ActionResult AcceptVerbsAttribute默认HTTP方法?

[AcceptVerbs(HttpVerbs.Get)] 
public ActionResult Index() { 
    ... 
} 

但我想知道:哪个HTTP方法一个ActionResult方法将接受没有明确的[AcceptVerbs(...)属性?

我会假设这是GETHEADPOST但只是想仔细检查。

谢谢。

+0

我的猜测是任何(包括PUT,DELETE)。我想你可以通过实验找出 - 在没有AcceptVerbs属性的情况下做一个简单的测试操作,对它发出一些不同的请求,看看会发生什么。我很想知道答案:-) – 2009-07-02 10:53:42

回答

5

没有AcceptVerbsAttribute您的Action将接受任何HTTP方法的请求。顺便说一句,你可以限制你的路由表中的HTTP方法:

routes.MapRoute(
    "Default",            // Route name 
    "{controller}/{action}/{id}",       // URL with parameters 
    new { controller = "Home", action = "Index", id = "" }, // Parameter defaults 
    new { HttpMethod = new HttpMethodConstraint(
     new[] { "GET", "POST" }) }       // Only GET or POST 
); 
+0

我不知道你可以通过RouteTable来限制HTTP方法 - 正是我之后所做的。谢谢。 – 2009-07-02 11:20:40

3

它会接受所有的HTTP方法。

看略有格式片段从ActionMethodSelector.cs(ASP.NET MVC源可以下载here):

private static List<MethodInfo> RunSelectionFilters(ControllerContext 
    controllerContext, List<MethodInfo> methodInfos) 
{ 
    // remove all methods which are opting out of this request 
    // to opt out, at least one attribute defined on the method must 
    // return false 

    List<MethodInfo> matchesWithSelectionAttributes = new List<MethodInfo>(); 
    List<MethodInfo> matchesWithoutSelectionAttributes = new List<MethodInfo>(); 

    foreach (MethodInfo methodInfo in methodInfos) 
    { 
     ActionMethodSelectorAttribute[] attrs = 
      (ActionMethodSelectorAttribute[])methodInfo. 
       GetCustomAttributes(typeof(ActionMethodSelectorAttribute), 
        true /* inherit */); 

     if (attrs.Length == 0) 
     { 
      matchesWithoutSelectionAttributes.Add(methodInfo); 
     } 
     else 
      if (attrs.All(attr => attr.IsValidForRequest(controllerContext, 
       methodInfo))) 
      { 
       matchesWithSelectionAttributes.Add(methodInfo); 
      } 
    } 

    // if a matching action method had a selection attribute, 
    // consider it more specific than a matching action method 
    // without a selection attribute 
    return (matchesWithSelectionAttributes.Count > 0) ? 
     matchesWithSelectionAttributes : 
     matchesWithoutSelectionAttributes; 
} 

所以,如果没有更好的匹配有明确的属性,操作方法操作方法,无需属性将使用。

相关问题