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

我想动态获取ASP.NET应用程序的绝对根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视图中使用它:

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....