什么是ActionResult AcceptVerbsAttribute默认的HTTP方法?

时间:2009-07-02 10:47:35

标签: asp.net-mvc

我知道您可以通过添加AcceptVerbsAttribute来限制特定ActionResult方法响应的HTTP方法,例如

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

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

我认为它是 GET HEAD POST ,但只是想仔细检查。

感谢。

2 个答案:

答案 0 :(得分:5)

如果没有AcceptVerbsAttribute,您的Action将接受任何HTTP方法的请求。顺便说一句,您可以在RouteTable中限制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
);

答案 1 :(得分: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;
}

因此,如果没有更好的匹配动作方法和显式属性,将使用没有属性的动作方法。