1

if i have an route like /foo/bar/pewpew .. is it possible to get an instance of the controller which that route maps too?

5
  • should be... is foo your controller? could you define what each part of your url represents? Commented Aug 8, 2011 at 12:46
  • What do you mean with "return a controller" and what is the controller in your example? Commented Aug 8, 2011 at 12:46
  • 1
    @Henk: Whatever ASP.Net would instantiate if you navigate to that URL. Commented Aug 8, 2011 at 12:48
  • Where are you planning to use this instance? the MvcHandler does the work of mapping the route values to a controller (which it requests via the ControllerBuilder/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. Commented Aug 8, 2011 at 12:48
  • @Matthew Abbot : custom error handling. Previous SO question: stackoverflow.com/questions/6972521/… Commented Aug 8, 2011 at 12:52

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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).
Hmmm .. not sure why it was removing the @SLaks word from my previous comment... ??
@Pure: You don't need to @-address the person who wrote the post you're commenting on.
@Pure:I think all you need is Request.Url. Try it and see if you get an exception.
Looking at the source, you only need AppRelativeCurrentExecutionFilePath and PathInfo, as well as any properties used by custom IRouteConstraints.
1

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.