if i have an route like /foo/bar/pewpew .. is it possible to get an instance of the controller which that route maps too?
2 Answers
To get the controller name, you can call create a fake HttpContextBase that returns your URL in its Request, then pass it to RouteTable.Routes.GetRouteData and check the area and controller values.
To get the controller instance, pass a RequestContext consisting of that HttpContextBase and RouteData to ControllerBuilder.Current.GetControllerFactory.CreateController.
5 Comments
Pure.Krome
creating a fake
HttpContextBase :: which (bare minimum) properties will I need to override for GetRouteData to not throw an exception? (and the rest of the answer makes sense).Pure.Krome
Hmmm .. not sure why it was removing the @SLaks word from my previous comment... ??
SLaks
@Pure: You don't need to
@-address the person who wrote the post you're commenting on.SLaks
@Pure:I think all you need is
Request.Url. Try it and see if you get an exception.SLaks
Looking at the source, you only need
AppRelativeCurrentExecutionFilePath and PathInfo, as well as any properties used by custom IRouteConstraints.Try,
var wrapper=new HttpContextWrapper(System.Web.HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(wrapper);
var controller = ControllerBuilder.Current.GetControllerFactory().CreateController(new RequestContext(wrapper, routeData), routeData.Values["controller"].ToString());
Update, you can use this instead.
var wrapper = new HttpContextWrapper(new System.Web.HttpContext(new HttpRequest(null, "http://localhost:4836/", null), new HttpResponse(new StringWriter())));
1 Comment
Pure.Krome
System.Web.HttpContext.Current might not be the url i wish to use. In fact, it will never be the correct url in my scenario's.
fooyour controller? could you define what each part of your url represents?MvcHandlerdoes the work of mapping the route values to a controller (which it requests via theControllerBuilder/DependencyResolver). You user code really starts within a controller already, so what are you trying to do? A use case would be nice point to start.