I need to use Server.MapPath. Since library projects does not have Startup.cs i cannot apply the normal way.
Asked
Active
Viewed 1,050 times
4
-
.NET 5 is .NET *Core* 5. The question is unclear, but if you google for `Server.MapPath ASP.NET Core` you'll find a lot of answers. – Panagiotis Kanavos Jun 10 '21 at 12:02
-
1Does this answer your question? [What is the equivalent of Server.MapPath in ASP.NET Core?](https://stackoverflow.com/questions/49398965/what-is-the-equivalent-of-server-mappath-in-asp-net-core) – Panagiotis Kanavos Jun 10 '21 at 12:02
-
So your real question should be: _How do I get a reference to IWebHostEnvironment inside a library project? (and inside a static class)_ – Steve Jun 10 '21 at 12:05
-
Yes, I will submit as you said – heimzza Jun 10 '21 at 12:37
-
This might be helpful and resolve your puzzle. [LINK](https://stackoverflow.com/questions/64482399/how-to-use-iwebhostenvironment-inside-static-class-in-asp-core). Here a static class which have property as `IWebHostEnvironment`. You can call initialize from startup.cs and then use it across your application. – Pashyant Srivastava Jun 10 '21 at 16:52
-
[Link]https://stackoverflow.com/questions/64482399/how-to-use-iwebhostenvironment-inside-static-class-in-asp-core This is the answer – heimzza Jun 11 '21 at 11:16
2 Answers
5
First, register HttpcontextAccessor service in Startup.cs of the project which uses the Library project,
services.AddHttpContextAccessor();
then in the class,
private static HttpContext _httpContext => new HttpContextAccessor().HttpContext;
private static IWebHostEnvironment _env => (IWebHostEnvironment)_httpContext.RequestServices.GetService(typeof(IWebHostEnvironment));
now you can access it in a static class and a static method.
This did the trick for me. If anyone needs.

heimzza
- 276
- 4
- 12
1
Another possible solution in .NET 6.0 is as follows:
public static class MainHelper
{
public static IWebHostEnvironment _hostingEnvironment;
public static bool IsInitialized { get; private set; }
public static void Initialize(IWebHostEnvironment hostEnvironment)
{
if (IsInitialized)
throw new InvalidOperationException("Object already initialized");
_hostingEnvironment = hostEnvironment;
IsInitialized = true;
}
}
Register HttpcontextAccessor and send parameters to Initialize in Program.cs
builder.Services.AddHttpContextAccessor();
MainHelper.Initialize(builder.Environment);
Now you can use _hostingEnvironment in any where in your project like following:
var path = MainHelper._hostingEnvironment.ContentRootPath;
or
var path = MainHelper._hostingEnvironment.WebRootPath;

Adeel Ahmed
- 147
- 9