How to get RouteData by URL?

前端 未结 2 1786
小蘑菇
小蘑菇 2020-11-28 10:39

I need to get RoutData by given URL string in ASP.NET MVC application.

I\'ve found the way that I need to mock HttpContextBase based on my

相关标签:
2条回答
  • 2020-11-28 10:57

    I used Moq to determine what members of HttpContextBase are used in GetRouteData(). They are:

    • Request
      • AppRelativeCurrentExecutionFilePath
      • PathInfo

    Request.AppRelativeCurrentExecutionFilePath should return path with ~, what I exactly need, so utility class may be like this one:

    public static class RouteUtils
    {
        public static RouteData GetRouteDataByUrl(string url)
        {
            return RouteTable.Routes.GetRouteData(new RewritedHttpContextBase(url));
        }
    
        private class RewritedHttpContextBase : HttpContextBase
        {
            private readonly HttpRequestBase mockHttpRequestBase;
    
            public RewritedHttpContextBase(string appRelativeUrl)
            {
                this.mockHttpRequestBase = new MockHttpRequestBase(appRelativeUrl);
            }
    
    
            public override HttpRequestBase Request
            {
                get
                {
                    return mockHttpRequestBase;
                }
            }
    
            private class MockHttpRequestBase : HttpRequestBase
            {
                private readonly string appRelativeUrl;
    
                public MockHttpRequestBase(string appRelativeUrl)
                {
                    this.appRelativeUrl = appRelativeUrl;
                }
    
                public override string AppRelativeCurrentExecutionFilePath
                {
                    get { return appRelativeUrl; }
                }
    
                public override string PathInfo
                {
                    get { return ""; }
                }
            }
        }
    }
    

    Then, you can use it like this (for example on ~/Error/NotFound):

    var rd = RouteUtils.GetRouteDataByUrl("~/Error/NotFound")
    

    Which should return an object that looks like this:

    RouteData.Values
    {
        controller = "Error",
        action = "NotFound"
    }
    
    0 讨论(0)
  • 2020-11-28 11:08

    This works for me (.NET 4.5, MVC 5): https://average-joe.info/url-to-route-data/

    System.Web.Routing.RouteData routeFromUrl =
        System.Web.Routing.RouteTable.Routes.GetRouteData(
                new HttpContextWrapper(
                    new HttpContext(
                        new HttpRequest(null, path, query),
                        new HttpResponse(new System.IO.StringWriter()))));
    
    0 讨论(0)
提交回复
热议问题