How to use private action method in .net mvc?

How can I use the private action method in the controller? when I used a private method, it is not available. it throws an error because "resource not found".

private ActionResult Index() { return View(); } 
+5
source share
1 answer

You can use the private / secure ActionResult to exchange 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 the framework can only be called by public methods (see source below). This is by design.

From the inner 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 } 

Typically, the controller has non-public code, and automatic routing of all methods will violate expected behavior and increase the attack area.

+5
source

Source: https://habr.com/ru/post/1202212/


All Articles