How to trigger a controller action with attributes used / applied in ASP.NET MVC?

When I try to call a specific action (method) of the controller from another action (method) of the controller, the attributes that were applied to the action that I call are not applied / not applied.

For example, if I have a Controller action with some attributes that apply like this:

[Authorize] [HttpPost] public ActionResult SaveUsers(List<User> users) { .. } 

and then I call this action from another Controller action, the attributes are not executed / forced.

MVC seems to control the execution of this ActionFilterAttribute / ActionMethodSelectorAttribute in its default implementation of "ActionInvoker" by default, but unfortunately, when you use ActionInvoker directly, it does not return the result of the method action, but simply calls the action and writes it directly to the response stream.

My goal is :

  • calling a specific action method
  • have attributes executable / executable
  • get the result of the method

I managed to make 1 and 3, but not 2.

+4
source share
1 answer

You can try to explicitly go through ActionInvoker. This is an object that performs your actions normally, but it is called by the MVC pipeline. In your original action, do the following:

 this.ActionInvoker.InvokeAction(this.ControllerContext, "TargetActionName"); 

This may work, but you enter the action name as a string, which is not very good.

+3
source

All Articles