I am trying to get the path to a folder in my website root and save it to a class property when my controller constructor is called:
public TestController:Controller{
string temp;
public TestController(){
temp = "";
}
}
I have tried the following:
temp = Server.MapPath("~/TheFolder/"); // Server is null - error.
temp = Request.PhysicalApplicationPath + @"TheFolder\"; // Request is null - error.
Any ideas?
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. The IHostingEnvironment is an interface for .
ASP.NET Core MVC controllers request dependencies explicitly via constructors.
Because the MapPath method maps a path regardless of whether the specified directories currently exist, you can use the MapPath method to map a path to a physical directory structure, and then pass that path to a component that creates the specified directory or file on the server.
What Is Model Binding? ASP.NET MVC model binding allows mapping HTTP request data with a model. It is the procedure of creating . NET objects using the data sent by the browser in an HTTP request. Model binding is a well-designed bridge between the HTTP request and the C# action methods.
AppDomain.CurrentDomain.BaseDirectory will give you the root of your site. So:
temp = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TheFolder");
(Update thanks to Marc Gravell's comment)
Do you actually need this path during the constructor? If you don't need it until the main page cycle begins, consider deferring it - just using a regular property; something like
public string BasePath {
get { return Server.MapPath("~/TheFolder/"); }
}
Then when this is used during the page cycle, it should be fine. You could cache it if you really want to, but I don't imagine this is going to be a bottleneck:
private string basePath;
public string BasePath {
get {
if(basePath == null) basePath = Server.MapPath("~/TheFolder/");
return basePath;
}
}
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