【问题标题】:ASP.NET MVC - how to get a full path to an actionASP.NET MVC - 如何获取操作的完整路径
【发布时间】:2011-10-10 15:12:49
【问题描述】:

在视图内部,我可以获取操作的完整路线信息吗?

如果我在控制器 MyController 中有一个名为 DoThis 的操作。我可以到达"/MyController/DoThis/" 的路径吗?

【问题讨论】:

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


    【解决方案1】:

    您的意思是喜欢在 Url 帮助器上使用 Action 方法:

    <%= Url.Action("DoThis", "MyController") %>
    

    或在 Razor 中:

    @Url.Action("DoThis", "MyController")
    

    这将为您提供一个相对 url (/MyController/DoThis)。

    如果你想获得一个绝对网址(http://localhost:8385/MyController/DoThis):

    <%= Url.Action("DoThis", "MyController", null, Request.Url.Scheme, null) %>
    

    【讨论】:

      【解决方案2】:

      几天前,我写了一篇关于这个主题的博客文章(见How to build absolute action URLs using the UrlHelper class)。正如 Darin Dimitrov 所说:如果明确指定了 protocol 参数,UrlHelper.Action 将生成绝对 URL。

      但是,为了可读性,我建议编写一个自定义扩展方法:

      /// <summary>
      /// Generates a fully qualified URL to an action method by using
      /// the specified action name, controller name and route values.
      /// </summary>
      /// <param name="url">The URL helper.</param>
      /// <param name="actionName">The name of the action method.</param>
      /// <param name="controllerName">The name of the controller.</param>
      /// <param name="routeValues">The route values.</param>
      /// <returns>The absolute URL.</returns>
      public static string AbsoluteAction(this UrlHelper url,
          string actionName, string controllerName, object routeValues = null)
      {
          string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
      
          return url.Action(actionName, controllerName, routeValues, scheme);
      }
      

      然后可以像这样调用该方法:@Url.AbsoluteAction("SomeAction", "SomeController")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-31
        • 2011-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-03
        • 1970-01-01
        相关资源
        最近更新 更多