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

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

问题描述

我的技能让我失望了,我知道我已经看过相关的代码,但我找不到.

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

获取任意 URL、通过 asp.net mvc 路由系统运行它并在另一端引用控制器实例的最快方法是什么?

例如,代码执行在某个任意控制器方法中.我想做这样的事情:

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???)

我正在尝试像路由系统一样获取控制器的实例,而不管代码在哪里执行.我不清楚此时如何将这些部分组合在一起.虽然我最终会发现它,但我想我可以通过在这里询问来节省时间 ;)

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 对象中获取RouteData 对象的最快方法是什么?任意网址.

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.

而且我知道的唯一方法是使用 Moq:

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天全站免登陆