Run a Controller action from inside another Controller as the current User

manually creating a controller and running its action does not run as the logged in user

If you want to run an action of another controller from inside a separate controller, it will work fine *if* you do not need any current HttpContext values such as User, etc. If you want to do that, you will need to force that context into the controller instance. To do this, I added a simple method to my base Controller class:
public T RunAsCurrentUser(
    T controller, RouteData routeData = null) 
        where T : ControllerBase
    var newContext = new ControllerContext(
        new HttpContextWrapper(
            routeData ?? new RouteData(), controller);
    controller.ControllerContext = newContext;
    return controller;

then to use it:
var someController = RunAsCurrentUser(
    new Some.NameSpace.SomeController());
var result = someController.SomeAction();

Comments (2) -

  • On a completely unrelated note, where do you host your website? It loads so much faster than mine!
Comments are closed