My skills are failing me, and I know I’ve seen the code around for this but I can’t find it.
What’s the quickest way to take any arbitrary URL, run it through your asp.net mvc routing system, and come out with a reference to a controller instance on the other end?
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 😉
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:
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!