获取有关URL的路由信息

时间:2014-11-11 20:55:28

标签: asp.net asp.net-mvc asp.net-mvc-5

我有一个ASP.NET MVC网站,需要显示存储在数据库中的用户提供的URL。它们显示的方式将有所不同,具体取决于如果该URL指向网站本身,该URL的路由方式。

例如,假设网站为 foo.com

  • 存储在DB中的URL:foo.com/pie/3/nutrition
    • 控制器是" pie"
    • 行动是"营养"
    • ID为3

链接格式化的方式取决于所有这三种方式。

如何正确提取此信息?我可以查询URL路由设备吗?

注意:"使用正则表达式"答案类型我不感兴趣 - 网站,操作或控制器名称可能会更改,网站可通过多个站点名称和端口等访问...

2 个答案:

答案 0 :(得分:3)

您可能会发现this blog帖子中说明的RouteInfo课程有用:

public class RouteInfo
{
    public RouteData RouteData { get; private set; }

    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)
        {
            this.request = new InternalRequestContext(uri, applicationPath);
        }

        public override HttpRequestBase Request 
        { 
            get { return this.request; } 
        }
    }

    private class InternalRequestContext : HttpRequestBase
    {
        private readonly string appRelativePath;
        private readonly string pathInfo;

        public InternalRequestContext(Uri uri, string applicationPath)
        {
            this.pathInfo = uri.Query;

            if (string.IsNullOrEmpty(applicationPath) || !uri.AbsolutePath.StartsWith(applicationPath, StringComparison.OrdinalIgnoreCase))
            {
                this.appRelativePath = uri.AbsolutePath.Substring(applicationPath.Length);
            }
            else
            {
                this.appRelativePath = uri.AbsolutePath;
            }
        }

        public override string AppRelativeCurrentExecutionFilePath 
        { 
            get { return string.Concat("~", appRelativePath); } 
        }

        public override string PathInfo 
        { 
            get { return this.pathInfo; } 
        }
    }
}

您可以像这样使用它:

public ActionResult Index()
{
    Uri uri = new Uri("http://foo.com/pie/3/nutrition");
    RouteInfo routeInfo = new RouteInfo(uri, this.HttpContext.Request.ApplicationPath);

    RouteData routeData = routeInfo.RouteData;

    string controller = routeData.GetRequiredString("controller");
    string action = routeData.GetRequiredString("action");
    string id = routeData.Values["id"] as string;
    ...
}

答案 1 :(得分:0)

关于单元测试的部分:scott guthrie blog post

你可以这样做:

MockHttpContext httpContxt = new MockHttpContext("foo.com/pie/3/nutrition");
RouteData routeData = new routes.GetRouteData(httpContext);

其中routes是您用于在应用程序中初始化路由的RouteCollection。然后你可以询问routeData [“controller”]等

该帖子是关于MVC的早期版本,因此从那时起类名可能已经发生了变化。