asp.net-mvc – 如何通过URL获取RouteData?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何通过URL获取RouteData?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要通过ASP.NET MVC应用程序中给定的URL字符串获取RoutData。

我发现了我需要模拟HttpContextBase基于我的URL字符串,然后将其传递给RouteTable.Routes.GetRouteData()方法Route Parsing (Uri to Route)线程的方式。

如何模拟HttpContextBase通过URL字符串使用RouteTable.Routes.GetRouteData()检索RouteData?
还是有另一种方法来通过URL检索RouteData?

解决方法

我使用 Moq来确定HttpContextBase的什么成员在GetRouteData()中使用。他们是:

>请求

> AppRelativeCurrentExecutionFilePath
> PathInfo

Request.AppRelativeCurrentExecutionFilePath应该返回路径〜,我真正需要的,所以实用程序类可能是这样的:

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 ""; }
            }
        }
    }
}

如果你传递〜/ Error / NotFound,例如,RouteUtils.GetRouteByUrl(“〜/ Error / NotFound”)返回类似

RouteData.Values
{
    controller = "Error",action = "NotFound"
}

也许这将有助于任何人。

原文链接:https://www.f2er.com/aspnet/253989.html

猜你在找的asp.Net相关文章