I need to use Server.MapPath. Since library projects does not have Startup.cs i cannot apply the normal way.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With