Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 3.1 Get wwwroot Path In Separate Class Library

Tags:

asp.net-core

Previously, I could access IHostingEnvironment using DI and pass that into my separate class library to get the wwwroot path, but in 3.1, IHostingEnvironment is being deprecated and it's suggested to use IWebHostEnvironment. For the life of me, I can't find a NuGet package to add to gain access to that object. I've tried Microsoft.AspNetCore.Hosting and Microsoft.AspNetCore.Hosting.Abstractions with no luck. Anyone? If it's no longer possible using this method, can someone propose a solution so that I can map a path to the wwwroot folder for my application?

like image 252
clockwiseq Avatar asked Dec 18 '19 22:12

clockwiseq


People also ask

How do I get wwwroot path in .NET Core?

The path of the wwwroot folder is accessed using the interfaces IHostingEnvironment (. Net Core 2.0) and IWebHostEnvironment (. Net Core 3.0) in ASP.Net Core.

How do I access wwwroot?

in the wwwroot folder as shown below. You can access static files with base URL and file name. For example, we can access above app. css file in the css folder by http://localhost:<port>/css/app.css .

What should be in the wwwroot folder?

The wwwroot folder is new in ASP.NET 5.0. All of the static files in your project go into this folder. These are assets that the app will serve directly to clients, including HTML files, CSS files, image files, and JavaScript files.


2 Answers

The link by poke about seeing the documentation is an answer but since links can die, here is the solution.

As of .NET Core 3.0, projects using the Microsoft.NET.Sdk.Web MSBuild SDK implicitly reference the shared framework. Projects using the Microsoft.NET.Sdk or Microsoft.NET.Sdk.Razor SDK must reference ASP.NET Core to use ASP.NET Core APIs in the shared framework.

In you project file, add this...

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>
like image 186
John81 Avatar answered Oct 04 '22 16:10

John81


To expand on John81's answer a bit: The relevant section of the Microsoft docs state:

To reference ASP.NET Core, add the following <FrameworkReference> element to your project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

</Project>

Referencing ASP.NET Core in this manner is only supported for projects targeting .NET Core 3.x.

Note the TargetFramework is netcoreapp3.0, which complies with the statement above that this only works for projects targeting .NET Core 3.x. Most library projects target some version of netstandard, so you need to change the <targetFramework> element in addition to adding the <FrameworkReference>.

like image 37
Bob.at.Indigo.Health Avatar answered Oct 04 '22 16:10

Bob.at.Indigo.Health