在HttpContext.Current返回null时如何操作

WEB API 控制类(v2.1)中,异步线程中,想获取存储绝对路径,
可以参考下面几种比较方法:

HttpRuntime.AppDomainAppPath
public static string AppDomainAppPath
{
    get
    {
        // 应用程序根目录物理路径,末尾带反斜杠
        return HttpRuntime.AppDomainAppPath;
    }
}

 

AppDomain.CurrentDomain.BaseDirectory
public static string BaseDirectory
{
    get
    {
        return AppDomain.CurrentDomain.BaseDirectory;
    }
}

 

示例,在你的项目中,创建了一个临时目录Temp时,
在代码中,你可以这样访问到其物理路径:

 public static string TempDirectory
 {
     get
     {
         // 使用 HostingEnvironment.MapPath 获取目录,不依赖 HttpContext
         string tempDirectory = HostingEnvironment.MapPath("~/Temp/");
         if (!Directory.Exists(tempDirectory))
             Directory.CreateDirectory(tempDirectory);

         return tempDirectory;
     }
 }

 

现实中,上传文件经Web API异步上传,在异步中,调用HttpContext.Current.Server.MapPath(),往往得到的是null。
你可以异步开始前调用是没有问题的。
2026-09-09_03-39-10

 

但是,如果你觉得这样复杂,你可以在需要地方:
 HttpContext context = HttpContext.Current;
 if (context != null)
 {
     context.Server.MapPath("~/Temp");
 }

 

不过Insus.NET还是较喜欢博文开头的的2个property:
HttpRuntime.AppDomainAppPath 和AppDomain.CurrentDomain.BaseDirectory


延申方法,重写MapPath方法:
2026-09-09_03-53-15

public static string MapPath(string virtualPath)
{
    if (HttpContext.Current != null)
    {
        return HttpContext.Current.Server.MapPath(virtualPath);
    }
    else
    {
        string path = virtualPath.Replace("~/", "\\");
        path = path.Replace("/", "\\");
        if (path.StartsWith("\\"))
        {
            path = path.TrimStart('\\');
        }
        return System.IO.Path.Combine(BaseDirectory, path);
    }
}
View Code

 

posted @ 2026-09-09 04:00  Insus.NET  阅读(3)  评论(0)    收藏  举报