手动从任意URL实例化一个控制器实例吗? [英] Manually instantiate a Controller instance from an arbitrary URL?

查看:105
本文介绍了手动从任意URL实例化一个控制器实例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的技能都没有了我,我知道我已经看到了code周围,但我不能找到它。

My skills are failing me, and I know I've seen the code around for this but I can't find it.

什么是采取任意网址,通过您的asp.net的MVC路由系统运行它,并与参照控制器实例在另一端出来的最快方法?

例如,code执行是里面的一些任意的控制器方法。我想要做这样的事情:

For example, code execution is inside some arbitrary controller method. I want to do something like this:

...
string myURL = "http://mysite/mycontroller/myaction/myparameters";

RouteData fakeRouteData = new RouteData(Route???, IRouteHandler???)
RequestContext ctxt = new RequestContext(this.ControllerContext.HttpContext,
                                         fakeRouteData);

ControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
Controller result = factory.CreateController(ctxt, controllername???)

我试图让就像路由系统做了控制器的情况下,无论在何处code正在执行的。我不清楚如何在这一点上拼起来。虽然我最终会发现它,我以为我可以问这里节省时间;)

I'm trying to get an instance of a controller just like the routing system does, regardless of where the code is executing. I'm unclear as to how to fit the pieces together at this point. While I will eventually discover it, I thought I could save time by asking here ;)

推荐答案

嗯...我不知道这是最好的解决方案,因为它需要嘲讽,但也许这会有所帮助。你是在正确的轨道上,并在控制器工厂的部分很简单,一旦你知道的什么的控制器来实例化,所以这个问题是什么,从获得的的RouteData 对象的最快方法任意URL。

Hmm... I don't know if this is the best solution because it requires mocking, but maybe this will help. You're on the right track and the controller factory part is simple once you know what controller to instantiate, so the question is what's the fastest way to get a RouteData object from an arbitrary url.

我知道怎么会像这样,与起订量的唯一方法:

And the only way I know how would be like so, with Moq:

string url = "~/Account/LogOn";  //trying to create Account controller in default MVC app

RouteCollection rc = new RouteCollection();
MvcApplication.RegisterRoutes(rc);
System.Web.Routing.RouteData rd = new RouteData();
var mockHttpContext = new Moq.Mock<HttpContextBase>();
var mockRequest = new Moq.Mock<HttpRequestBase>();
mockHttpContext.Setup(x => x.Request).Returns(mockRequest.Object);
mockRequest.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns(url);

RouteData routeData = rc.GetRouteData(mockHttpContext.Object);

string controllerName = routeData.Values["controller"].ToString();

IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(this.ControllerContext.RequestContext, controllerName);

我做了相当多的谷歌搜索,但没有找到太多,没有涉及到单元测试/嘲讽。我不知道是否有的一个快速和容易做到这一点,但肯定想知道,如果有人有更好的解决方案!

I did quite a bit of googling and couldn't find much that didn't pertain to unit testing/mocking. I don't know if there is a quick and easy to do this, but would certainly like to know if someone has a better solution!

这篇关于手动从任意URL实例化一个控制器实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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