ASP.NET Core 3.1 WebRoot Path

二次信任 提交于 2021-02-08 10:38:50

问题


I am pushing an external file into the wwwroot folder of my ASP.NET Core 3.1 application. I need to reference the path to provide a constructor variable during the services wire up.

In the Startup class I have added the IWebHostEnvironment to the constructor parameters:

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

When debugging, it seems that _env.WebRootPath returns the path as it is in my source folder, rather than the path being executed, i.e.

It returns: <path to my source code>/wwwroot

Instead of the execution relative path: <path to my source code>/bin/Debug/netcoreapp3.0/wwwroot

How do i get it to return the correct, execution relative path?


回答1:


It's because by default the content-root path is the directory where the project is located rather than its output.

If you want to change that behavior, you have to call this line when building the web-host.

.UseContentRoot(AppContext.BaseDirectory);

Then the path will change to <ProjectPath>\Debug\netcoreapp3.1 or whatever you are compiling to.




回答2:


Maybe try something like the following:

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

For further information/help take a glance on this article: Getting the Root Directory Path for .Net Core Applications




回答3:


It worked for me

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


来源:https://stackoverflow.com/questions/60600473/asp-net-core-3-1-webroot-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!