asp.net - 如何获取网站根 URL?

标签 asp.net

我想动态获取 ASP.NET 应用程序的绝对根 Url。这需要是应用程序的完整根 URL,格式为:http(s)://hostname(:port)/

我一直在使用这个静态方法:

public static string GetSiteRootUrl()
{
    string protocol;

    if (HttpContext.Current.Request.IsSecureConnection)
        protocol = "https";
    else
        protocol = "http";

    StringBuilder uri = new StringBuilder(protocol + "://");

    string hostname = HttpContext.Current.Request.Url.Host;

    uri.Append(hostname);

    int port = HttpContext.Current.Request.Url.Port;

    if (port != 80 && port != 443)
    {
        uri.Append(":");
        uri.Append(port.ToString());
    }

    return uri.ToString();
}

但是,如果范围内没有 HttpContext.Current 怎么办? 我在 CacheItemRemovedCallback 中遇到过这种情况。

最佳答案

对于 WebForms,此代码将返回应用程序根的绝对路径,无论应用程序的嵌套程度如何:

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + ResolveUrl("~/")

上面的第一部分返回应用程序的方案和域名 (http://localhost),不带尾部斜杠。 ResolveUrl 代码返回应用程序根目录 (/MyApplicationRoot/) 的相对路径。通过将它们组合在一起,您可以获得 Web 表单应用程序的绝对路径。

使用 MVC:

HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~/")

或者,如果您尝试直接在 Razor View 中使用它:

@HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)@Url.Content("~/")

关于asp.net - 如何获取网站根 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5853294/

相关文章:

c# - 在 C# asp.net 中将字符串中的特定文本设为粗体

javascript - 为什么当我在我的 aspx 页面中的 html 图像点击事件中调用 JavaScript 函数时,我的网页正在刷新?

c# - t4 模板相对于 Class 文件的优势

c# - 将 IEnumerable<string> 转换为 IEnumerable<ListItem>

asp.net - “The ' Microsoft.Jet.OLEDB.4.0 ' provider is not registered on the local machine”…DNN

c# - 如何获取 List<t> 项的字符串值

asp.net - DataList 中的分页不起作用

c# - 如何在 .net 中将 html 内容写入 pdf

javascript 在使用母版页的内容页面中不起作用

asp.net - 有没有办法在不指定 IdenitityUser、IdentityRole 和 IdentityDbContext 上的 TKey 的情况下创建自定义用户和角色?