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.

mawtex
  • 1,564
  • 1
  • 12
  • 21

1 Answers1

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Do what parts would I need to mock? – mawtex Feb 03 '11 at 03:26
  • 1
    @mawtex: Create an `HttpContextBase` class which returns your URL in its `Request.AppRelativeCurrentExecutionFilePath`. – SLaks Feb 03 '11 at 03: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 '11 at 04:56
  • 1
    Do you have a code sample to demosntrate? – Ciaran Gallagher Jan 16 '19 at 09:06
  • This is absolutely ancient now, but in the past, I used code based on this person's blog that uses this technique: https://blog.olamisan.com/how-to-determine-if-an-arbitrary-url-matches-a-defined-route. My minor extension to it: https://gist.github.com/lethek/9613978fa4ee7935bf34f9e68111e990 – lethek Mar 22 '22 at 23:50