在 Global.Asax 中获取相对根

本文关键字:相对 获取 Global Asax | 更新日期: 2023-09-27 18:36:25

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

我像这样做了物理路径:

    //Get the physical root and store it
    Global.ApplicationPhysicalPath = Request.PhysicalApplicationPath;

但我无法获得相对路径。我有以下有效的代码,但它需要将其放在page对象中:

Global.ApplicationRelativePath = Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, "") + Page.ResolveUrl("~/");

谢谢

在 Global.Asax 中获取相对根

为了获取application_start中的相对路径,请使用以下命令:

 protected void Application_Start(object sender, EventArgs e)
 {
     string path = Server.MapPath("/");
 }

在 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;
        }
    }