Last active
August 29, 2015 14:08
-
-
Save duncansmart/b41a7304030bb6da1022 to your computer and use it in GitHub Desktop.
GetRouteDataForPath: GetRouteData for a given path/URL (ASP.NET MVC)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web; | |
using System.Web.Routing; | |
public static class RouteUtils | |
{ | |
/// <summary> | |
/// e.g. <code>var routeData = RouteTable.Routes.GetRouteDataForPath("~/foo/bar");</code> | |
/// </summary> | |
/// <param name="routes"></param> | |
/// <param name="appRelativePath">e.g. "~/foo/bar"</param> | |
public static RouteData GetRouteDataForPath(this RouteCollection routes, string appRelativePath) | |
{ | |
return routes.GetRouteData(new MockContext(appRelativePath)); | |
} | |
class MockContext : HttpContextBase | |
{ | |
HttpRequestBase _request; | |
public MockContext(string appRelativePath) | |
{ | |
_request = new MockRequest(appRelativePath); | |
} | |
public override HttpRequestBase Request | |
{ | |
get { return _request; } | |
} | |
class MockRequest : HttpRequestBase | |
{ | |
string _appRelativePath; | |
public MockRequest(string appRelativeUrl) | |
{ | |
_appRelativePath = appRelativeUrl; | |
} | |
public override string AppRelativeCurrentExecutionFilePath | |
{ | |
get { return _appRelativePath; } | |
} | |
public override string PathInfo | |
{ | |
get { return ""; } | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment