小编Nev*_*veN的帖子

如何在 ASP Core 中的静态类中使用“IWebHostEnvironment”

有没有办法在 ASP Core 的静态类中使用“IWebHostEnvironment”?

我的课 :

public class MainHelper
{
    private readonly IWebHostEnvironment _hostingEnvironment;

    public MainHelper(IWebHostEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }    

    public static void SaveFile(IFormFile file)
    {
            var path = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            using (var fileStream = System.IO.File.Create(Path.Combine(path, file.FileName)))
            {
                file.CopyTo(fileStream);
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的行有错误:

var path = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
Run Code Online (Sandbox Code Playgroud)

错误: c# 会话非静态字段方法或属性“MainHelper._hostingEnvironment”需要对象引用

请指教

c# dependency-injection class static-classes .net-core

4
推荐指数
1
解决办法
7158
查看次数