Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASPNET Core: Wrong Value for ContentRootPath

I have an ASP.NET core application with the following configurations:

public Startup(IHostingEnvironment hostingEnvironment)
{
    _configuration = new ConfigurationBuilder()
        .SetBasePath(hostingEnvironment.ContentRootPath)
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", true)
        .AddEnvironmentVariables()
        .Build();
}

When I publish the application and run it using the dotnet MyApp.dll inside the application directory, it runs with no problems. When I execute the the command dotnet /dir1/dir2/MyApp.dll, it fails to load the appsettings.json file. I did a little digging and found out that the ContentRootPath is set to the directory I'm running the dotnet command from and not the actual directory of the application. Can anyone tell me how to fix this issue?

like image 239
boring91 Avatar asked Jan 30 '17 11:01

boring91


1 Answers

I have the same problem. I often store my code in a /src folder which contains multiple projects. So from the CLI I would like to do the following:

cd /c/code/repo
dotnet restore /src/solution.sln
dotnet build /src/solution.sln
dotnet run /src/project/project.csproj

The first 2 work no problem but the CLI for .NET Core 2.0 does not recognize .SetBasePath(env.ContentRootPath) as the path where the project is being built to. Instead it uses the current path I am in on the CLI.

This results in:

Unhandled Exception: System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\code\repo\appsettings.json'.

The only way I can get it to work is if I go the that directory:

cd /src/project
dotnet run project.csproj

Which is fine but if I want to rebuild the solution then I need to navigate back to /src where my .sln is located which is very annoying.

Seems like a bug in the CLI.

like image 196
Stephen Weinrich Avatar answered Sep 28 '22 18:09

Stephen Weinrich