gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:21:30 26 4
gpt4 key购买 nike

我需要通过ASP.NET MVC应用程序中给定的URL字符串来获取RoutData

我已经找到了根据我的URL字符串模拟HttpContextBase并将其传递给Route Parsing (Uri to Route)线程中的RouteTable.Routes.GetRouteData()方法的方式。

如何模拟HttpContextBase以使用RouteData通过URL字符串检索RouteTable.Routes.GetRouteData()
还是有另一种通过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):

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

    哪个应该返回如下所示的对象:

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

    关于asp.net-mvc - 如何通过URL获取RouteData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3545432/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com