我可以手动创建一个Controller实例,然后以用户身份运行它吗? [英] Can I Create a Controller instance manually, then run it as a user?

查看:106
本文介绍了我可以手动创建一个Controller实例,然后以用户身份运行它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,从控制器中我想执行以下操作:

For example, from a controller I want to do something like this:

var controller = new SomeController(); //different controller
//as of now, the controller.User is null, I want to set it
controller.DoSomething();

我想设置用户,因为它使用角色来决定在这里做什么.我希望将所有角色处理留在该控制器中(而不是我的代码).有什么方法可以设置用户?还是可以像我从同一MVC项目中的另一个控制器调用此用户一样,以同一用户身份运行它?

I want to set the User as it uses the roles to decide what to do here. I would prefer to leave all the role handling in that controller (not my code). Is there any way to set the User? Or possibly run it as the same user as I am calling this from another controller in the same MVC project?

在我的Controller BaseClass中,在Sergey的帮助下,我的解决方案:

My solution after Sergey's help, in my Controller BaseClass:

public T RunControllerAsCurrentUser<T>(T controller, RouteData routeData = null) where T : ControllerBase
{
    var newContext = new ControllerContext(new HttpContextWrapper(System.Web.HttpContext.Current), routeData ?? new RouteData(), controller);
    controller.ControllerContext = newContext;
    return controller;
}

然后使用它:

var someController = RunControllerAsCurrentUser(new Some.NameSpace.SomeController());
var result = someController.SomeAction();

推荐答案

这取决于您使用的方法.如果您只需要执行方法,则可以尝试以下方法:

It depends what your method is using. If you just need to execute method then you can try something like that:

var factory = DependencyResolver.Current.GetService<IControllerFactory>() ?? new DefaultControllerFactory();
TestController controller = factory.CreateController(this.ControllerContext.RequestContext, "Test") as TestController;

RouteData route = new RouteData();
route.Values.Add("action", "Test"); // ActionName, but it not required

ControllerContext newContext = new ControllerContext(new HttpContextWrapper(System.Web.HttpContext.Current), route, controller);
controller.ControllerContext = newContext;
ActionResult result = controller.Test();

此方法将执行一些基本的控制器初始化,但是如果您的方法使用某些参数或请求特定数据,则可能需要在RouteData.Values中指定它们.

This approach will do some basic controller initialization, but if your method uses some parameters, or request specific data, then it might require specifying them in RouteData.Values.

尝试这种方法,并在注释中指出它是否对您有用.

Try this approach and tell in comments if it works for you or not.

这篇关于我可以手动创建一个Controller实例,然后以用户身份运行它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆