C# System.Web.HttpContext.Current.Server.MapPath 报错问题

  • 在后台线程里访问导致System.Web.HttpContext.Current==null,从而引发了报错
  • 去查看了下 官方文档,解释是 在线程中访问,未定义的现象
    在这里插入图片描述

https://docs.microsoft.com/zh-cn/dotnet/api/system.web.httpcontext?view=netframework-4.8

解决方案如下

  public static string GetPath(string path)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(path);//有http请求
            }
            else           
            {
                return System.Web.HttpRuntime.AppDomainAppPath.ToString()+ path;
            }
       }

猜你喜欢

转载自blog.csdn.net/qq_38110067/article/details/125617194