Иногда возникает потребность получить route-параметры для строки URL.
Для этого необходимо создать экземпляр RouteData из URL.
RouteInfo Class:
public class RouteInfo { public RouteData RouteData { get; private set; } public RouteInfo(RouteData data) { RouteData = data; } public RouteInfo(Uri uri, string applicationPath) { RouteData = RouteTable.Routes.GetRouteData(new InternalHttpContext(uri, applicationPath)); } private class InternalHttpContext : HttpContextBase { private readonly HttpRequestBase _request; public InternalHttpContext(Uri uri, string applicationPath) { _request = new InternalRequestContext(uri, applicationPath); } public override HttpRequestBase Request { get { return _request; } } } private class InternalRequestContext : HttpRequestBase { private readonly string _appRelativePath; private readonly string _pathInfo; public InternalRequestContext(Uri uri, string applicationPath) { _pathInfo = uri.Query; if (String.IsNullOrEmpty(applicationPath) || !uri.AbsolutePath.StartsWith(applicationPath, StringComparison.OrdinalIgnoreCase)) _appRelativePath = uri.AbsolutePath.Substring(applicationPath.Length); else _appRelativePath = uri.AbsolutePath; } public override string AppRelativeCurrentExecutionFilePath { get { return String.Concat("~", _appRelativePath); } } public override string PathInfo { get { return _pathInfo; } } } }
Пример использования:
Uri uri = new Uri("http://www.yoursite.com/somepage"); RouteInfo routeInfo = new RouteInfo(uri, HttpContext.Current.Request.ApplicationPath); // Here it is... RouteData routeData = routeInfo.RouteData;