Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use private action method in .net mvc?

Tags:

asp.net-mvc

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();
                }
like image 948
Samaskhan Avatar asked Sep 10 '14 06:09

Samaskhan


People also ask

Can action method be private 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. An action method cannot contain ref and out parameters.

Can ActionResult be private?

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...

What is the use of action method in MVC?

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.


1 Answers

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.

like image 113
Tim M. Avatar answered Sep 27 '22 22:09

Tim M.