gpt4 book ai didi

c# - 如何在 ASP Core 的静态类中使用 "IWebHostEnvironment"

转载 作者:行者123 更新时间:2023-12-05 08:49:10 27 4
gpt4 key购买 nike

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

我的类(class):

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

我的行有错误:

var path = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");

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

请指教

最佳答案

因为接受的答案是一个。但是如果有人提到在静态类中没有初始化就使用:

    using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

public class Common{
public static IWebHostEnvironment WebEnv()
{
var _accessor = new HttpContextAccessor();
return _accessor.HttpContext.RequestServices.GetRequiredService<IWebHostEnvironment>();
}
}

用法:

var path = Common.WebEnv().WebRootPath;

关于c# - 如何在 ASP Core 的静态类中使用 "IWebHostEnvironment",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64482399/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com