How can i use private action method in controller? when i used private method it is not accessible. it throws error as "resource not found".
private ActionResult Index()
{
return View();
}
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. An action method cannot contain ref and out parameters.
An ActionResult exists explicitly for the purpose of returning a result to the framework; It would make absolutely no sense for it to be private...
ASP.NET MVC Action Methods are responsible to execute requests and generate responses to it. By default, it generates a response in the form of ActionResult. Actions typically have a one-to-one mapping with user interactions.
You can use a private/protected ActionResult
to share logic between public actions.
private ActionResult SharedActionLogic( int foo ){
return new EmptyResult();
}
public ActionResult PublicAction1(){
return SharedActionLogic( 1 );
}
public ActionResult PublicAction2(){
return SharedActionLogic( 2 );
}
But only public action methods will ever be invoked by the framework (see source below). This is by design.
From the internal class ActionMethodSelector in System.Web.Mvc:
private void PopulateLookupTables()
{
// find potential matches from public, instance methods
MethodInfo[] allMethods = ControllerType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public);
// refine further if needed
MethodInfo[] actionMethods = Array.FindAll(allMethods, IsValidActionMethod);
// remainder of method omitted
}
It is common to have non-public code in a controller, and automatically routing all methods would violate expected behavior and increase attack footprint.
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