在Global.Asax中获得相对根

The*_*per 6 c# asp.net global global-variables

我试图在应用程序启动时将应用程序的物理根和相对根存储在内存中.

我做了这样的物理路径:

    //Get the physical root and store it
    Global.ApplicationPhysicalPath = Request.PhysicalApplicationPath;
Run Code Online (Sandbox Code Playgroud)

但我无法得到相对的道路.我有以下代码可以工作,但它需要将它放在一个page对象中:

Global.ApplicationRelativePath = Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, "") + Page.ResolveUrl("~/");
Run Code Online (Sandbox Code Playgroud)

谢谢

小智 2

在Global.asax中添加以下代码:

private static string ServerPath { get; set; }

protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        ServerPath = BaseSiteUrl;
    }

    protected static string BaseSiteUrl
    {
        get
        {
            var context = HttpContext.Current;
            if (context.Request.ApplicationPath != null)
            {
                var baseUrl = context.Request.Url.Scheme + "://" + context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/') + '/';
                return baseUrl;
            }
            return string.Empty;
        }
    }
Run Code Online (Sandbox Code Playgroud)