简体   繁体   中英

ASP.NET - What's the difference between ChildActionOnly and NonAction attributes?

Just out of curiosity, what's the difference between these two attributes?

NonAction and ChildActionOnly

Both attributes seems to do the very same to me. Preventing the pipeline (action invoker) to invoke the action method. Please have a look at this snippet:

[NonAction]
private ActionResult StackOverflow1()
{
    // Omitted for brevity.
    return View();
}

[ChildActionOnly]
private ActionResult StackOverflow2()
{
    // Omitted for brevity.
    return View();
}

Of course both methods won't be invoked due to the fact that they are private - at least at the default implementation - but I would like to know the difference just out of curiosity...

ChildActionOnly -- can only be called by another action and not directly from an external call (via routing). Permitted actions include Action/RenderAction extension methods.

NonAction -- Like marking a method "private" in regards to keeping it from being accessible from either an external call or as a child action. Good for protecting actions you don't need/want created as a direct view. Worth mentioning this is only necessary on public methods (as private/protected aren't considered "actionable").

See also:

An action method is a public method in a controller that can be invoked using a URL. So, by default, if you have any public method in a controller then it can be invoked using a URL request. To restrict access to public methods in a controller, NonAction attribute can be used.

Child action methods are different from NonAction methods, in that NonAction methods cannot be invoked using Action() or RenderAction() helpers.

Child action methods will not respond to URL requests. If an attempt is made, a runtime error will be thrown stating - Child action is accessible only by a child request.

Child action methods can be invoked by making child request from a view using Action() and RenderAction() Html helpers.

An action method doesn't need to have [ChildActionOnly] attribute to be used as a child action, but use this attribute to prevent if you want to prevent the action method from being invoked as a result of a user request.

Child actions are typically associated with partial views, although this is not compulsory.

Using child action methods, it is possible to cache portions of a view. This is the main advantage of child action methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM