15

I have a list of local URL’s and I need to determine if they are “valid MVC paths”. How can I check if a URL (path) maps to a MVC controller?

Phil Haack's Route Debugger will find a route that match the current request and does so using the current HttpContext. I would like to get this info without building up a mock HttpContext - if possible.

2
  • Type the path into the browser and check for 404?
    – Pierreten
    Feb 3, 2011 at 3:17
  • Do you want to check whether they're valid paths or valid MVC paths?
    – SLaks
    Feb 3, 2011 at 3:23

1 Answer 1

16

You can call RouteTable.Routes.GetRouteData with a mocked HttpContextBase.

The routes are matched internally using the request's AppRelativeCurrentExecutionFilePath.
However, this functionality is not exposed, so you need to pass an HttpContextBase.

You need to create an HttpContextBase class which returns an HttpRequestBase instance in its request property.
The HttpRequestBase class needs to return your path, beginning with ~/, in its AppRelativeCurrentExecutionFilePath property.

You don't need to implement any other properties, unless they're used by IRouteConstraints.

To check whether you got an MVC route, check whether the resulting routeData.Handler is MvcRouteHandler.

5
  • Do what parts would I need to mock?
    – mawtex
    Feb 3, 2011 at 3:26
  • 1
    @mawtex: Create an HttpContextBase class which returns your URL in its Request.AppRelativeCurrentExecutionFilePath.
    – SLaks
    Feb 3, 2011 at 3:29
  • 1
    I found your mention of the required AppRelativeCurrentExecutionFilePath very valuable as I am writing tests for this now. Wish I could vote up more than once :)
    – CRice
    Apr 15, 2011 at 4:56
  • 1
    Do you have a code sample to demosntrate? Jan 16, 2019 at 9:06
  • This is absolutely ancient now, but in the past, I used code based on this person's blog that uses this technique: blog.olamisan.com/…. My minor extension to it: gist.github.com/lethek/9613978fa4ee7935bf34f9e68111e990
    – lethek
    Mar 22, 2022 at 23:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.