Converting an absolute path to

I am trying to serve files from my images folder inside the wwwroot folder of my ASP.NET Core application, where I already enabled access to static files in the Startup class.

The HostingEnvironment service provides me the WebRootPath property, which provides me with the absolute path to the wwwroot folder, but using this path gives me the error "Not allowed to load local resource" in my browser console.

If I access the file from my browser using localhost + relative path, I can get the image file, so there is no authorization problem.

Now I need to convert this absolute path to relative for my web server.

+5
source share
2 answers

Given the error you receive, it seems to me that you are trying to use _env.WebRootPath + "/images/textfile.txt" in your views, for example, as an href attribute.

  • Doing this in a browser will try to ask your page for a URL that looks like file:///C:/Users/PathToYourSite/wwwroot/images/textfile.txt that ends with the error you are experiencing. You can learn more about this in this answer , but in browsers such as the Chrome modem, http protocol requests for the file protocol are disabled by default.

Therefore, the IHostingEnvironment approach should be used when you want to read the contents of a file as part of the server-side logic so that you can do something with them.

However, if you need to create links to your files in wwwroot and use them in your submissions, you have several options:

  • Use IUrlHelper to resolve the shared URL for the file inside wwwroot, where "~/" is the wwwroot folder. Then use it when you need it, like href:

     @Url.Content("~/images/textfile.txt") 
  • Directly create a razor binding with the href attribute, starting with "~/" . (You even get intellisense there)

     <a href="~/images/textfile.txt">Get file from wwwroot</a> 
+4
source

To access the file in wwwroot, enter IHostingEnvironment in the controller constructor:

 private IHostingEnvironment _env; public HomeController(IHostingEnvironment env) { _env = env; } 

Update your controller to read the WebRootPath property and add a relative file path to it.

 var content = System.IO.File.ReadAllText(_env.WebRootPath + "/images/textfile.txt"); 

This will read the entire contents of the file located inside /wwwroot/images/textfile.txt

Hope that helps

+3
source

All Articles