in Asp.Net MVC if I decorate an action method with attribute NonAction
then it wont be allowed to be called by the user visiting the site.
same happens when I make it private
So whats the difference between the two and is there a special purpose for which NonAction
attribute has been made?
For example whats the difference between
[NonAction]
public ActionResult SomeAction(){}
And
private ActionResult SomeAction(){}
in the context of asp.net MVC of course I know one is public
and the other one is private
The NonAction attribute is used when we want a public method in a controller but do not want to treat it as an action method. An action method is a public method in a controller that can be invoked using a URL. So, by default, if we have any public method in a controller then it can be invoked using a URL request.
So, every public method inside the Controller is an action method in MVC. Action Method can not be a private or protected method. If you provide the private or protected access modifier to the action method, it will provide the error to the user, i.e., “resource can not be found” as below.
To restrict access to public methods in a Controller, a Non-Action attribute can be used. Non-Action is another built-in attribute which indicates that a public method of a Controller is not an action method. It is used when we don't want that method to be treated as an action method.
That's the only difference. The attribute is used when you want a method that has a signature that would make it an action, but that you don't want to be an action.
An example for a use for that is a method that action methods call to produce the ActionResult
for them:
[NonAction]
public JsonResult JsonInfo(string id, string value) {
return Json(new { id = id, value = value });
}
public JsonResult GetBusInfo() {
return JsonInfo("4", "Bus");
}
public JsonResult GetCarInfo() {
return JsonInfo("8", "Car");
}
The reason to make it public instead of private would be so that actions in other controllers could also use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With