Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the ActionResult AcceptVerbsAttribute default HTTP methods?

Tags:

asp.net-mvc

I know you can restrict which HTTP methods a particular ActionResult method responds to by adding an AcceptVerbsAttribute, e.g.

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

But I was wondering: which HTTP methods an ActionResult method will accept without an explicit [AcceptVerbs(...)] attribute?

I would presume it was GET, HEAD and POST but was just wanting to double-check.

Thanks.

like image 360
Ian Oxley Avatar asked Jan 24 '23 11:01

Ian Oxley


2 Answers

Without AcceptVerbsAttribute your Action will accept requests with any HTTP methods. BTW you can restrict HTTP methods in your RouteTable:

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
);
like image 196
eu-ge-ne Avatar answered May 12 '23 04:05

eu-ge-ne


It will accept all HTTP methods.

Look at slightly formatted fragment from ActionMethodSelector.cs (ASP.NET MVC source could be downloaded 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;
}

So if there is no better matching action method with explicit attribute, action method without attributes will be used.

like image 38
Alexander Prokofyev Avatar answered May 12 '23 04:05

Alexander Prokofyev