ASP.NET Core 3.1 WebRoot Path



我正在将一个外部文件推送到我的ASP.NET Core 3.1应用程序的wwwroot文件夹中。在服务连接期间,我需要引用路径来提供构造函数变量。

在Startup类中,我将IWebHostEnvironment添加到构造函数参数中:

public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
_env = env;
}

调试时,似乎_env.WebRootPath返回的路径是我的源文件夹中的路径,而不是正在执行的路径,即

它返回:<path to my source code>/wwwroot

而不是执行相对路径:<path to my source code>/bin/Debug/netcoreapp3.0/wwwroot

如何让它返回正确的执行相对路径?

也许可以尝试以下方法:

var rootDir  = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

有关更多信息/帮助,请浏览本文:Getting the Root Directory Path For.Net Core Applications

这是因为默认情况下,内容根路径是项目所在的目录,而不是其输出。

如果你想改变这种行为,你必须在构建网络主机时调用这条线。

.UseContentRoot(AppContext.BaseDirectory);

然后路径将更改为<ProjectPath>Debugnetcoreapp3.1或您正在编译的任何文件。

private readonly IWebHostEnvironment _env;
public HomeController(IWebHostEnvironment env)
{
_env = env;
}
public ActionResult Index()
{
string contentRootPath = _env.ContentRootPath;
string webRootPath = _env.WebRootPath;
return Content(contentRootPath + "n" + webRootPath);
}

它对我有效

string applicationPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

最新更新