【问题标题】:Url helper for full url in asp.net mvc-3用于 asp.net mvc-3 中完整 url 的 Url 助手
【发布时间】:2011-08-17 08:37:09
【问题描述】:

写作

@Url.Content("~/Something/Something.html")

在剃须刀渲染中

/AppFolder/Something/Something.html

有没有一种方法可以呈现完整的 URL,例如 http://www.something.com/AppFolder/Something/Something.html,而不需要恶意攻击? (比如将协议和域存储在AppConfig 中,并将字符串连接到它)

有没有类似@Url.FullPath("~/asdf/asdf") 或类似的助手?

【问题讨论】:

标签: asp.net urlhelper asp.net-mvc-3


【解决方案1】:

请参阅this blog post 以获得答案。

基本上,您需要做的只是协议参数,例如

Url.Action("About", "Home", null, "http")

【讨论】:

  • 这比使用String.Format 更好。 +1
【解决方案2】:

@Url.RouteURL() 不会安静地回答这个问题。它确实适用于命名路由,但不适用于任意虚拟路径。 这是生成完整出站 url 的快速帮助方法。您可以根据所需的控制程度为各种方案 (http[s]) 创建重载。

public static class UrlHelperExtension
{
    public static string ContentFullPath(this UrlHelper url,string virtualPath)
    {
        var result = string.Empty;
        Uri requestUrl = url.RequestContext.HttpContext.Request.Url;

        result = string.Format("{0}://{1}{2}",
                               requestUrl.Scheme,
                               requestUrl.Authority, 
                               VirtualPathUtility.ToAbsolute(virtualPath));
        return result;
    }
}

【讨论】:

  • 这是个老问题!您可能会为此获得徽章:D
【解决方案3】:

对于需要在 WebAPI 2.2 和/或 MVC5 中构建 URL 的任何人,这对我有用:

// works in a controller
var requestUri = this.Request.RequestUri;
// just the http/s and the hostname; ymmv
string baseUrl = requestUri.Scheme + "://" + requestUri.Authority + "/";
// build your url for whatever purpose you need it for
string url = baseUrl + "SomeOtherController?id=" + <some_magic_value>;

【讨论】:

    【解决方案4】:

    您可以使用帮助程序生成完整的 url,包括协议。注意url.Action 中的第一个小写字母。

    var url = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
    var fullUrl = url.Action("YourAction", "YourController", new { id = something }, protocol: System.Web.HttpContext.Current.Request.Url.Scheme);
    

    输出

    https://www.yourdomain.com/YourController/YourAction?id=something

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      相关资源
      最近更新 更多