11

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

The HostingEnvironment service provides me with a WebRootPath property that provides me with an absolute path to the wwwroot folder but using this path gives me a "Not Allowed to load local resource" error in my browser's console.

If I access the file from my browser using localhost + the relative path I am able to get the image file so there is no issue about authorization.

All I need now is to be able to convert that absolute path into a relative one to my web server.

Tseng
  • 61,549
  • 15
  • 193
  • 205
Nabin Karki Thapa
  • 483
  • 1
  • 6
  • 18

3 Answers3

7

In order to access file in wwwroot, Inject the IHostingEnvironment into you controller constructor:

private IHostingEnvironment _env;

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

Update your controller to read the WebRootPath property and append the relative file path to it

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

This will read all the content of the file located inside /wwwroot/images/textfile.txt

Hope that helps

johnny 5
  • 19,893
  • 50
  • 121
  • 195
Hossam Barakat
  • 1,399
  • 9
  • 19
7

Given the error you are getting, 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 that will end up in the browser trying to request from your page a url that looks like file:///C:/Users/PathToYourSite/wwwroot/images/textfile.txt, which ends in the error you are experiencing. You can read more about that on this answer, but in browsers like moder Chrome, requests from the http protocol to the file protocol are disabled by default.

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

However if what you need is to generate the links to your files in wwwroot and use them in your views, you have a couple of options:

  • Use the IUrlHelper to resolve the public url to a file inside wwwroot, where "~/" is the wwwroot folder. Then use it whenever you need it, like an href:

    @Url.Content("~/images/textfile.txt")
    
  • Directly create an anchor in a razor view with an href attribute starting with "~/". (You even get intellisense there)

    <a href="~/images/textfile.txt">Get file from wwwroot</a>
    
Community
  • 1
  • 1
Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112
0

This works for newer version of .NET

public class TestController{
   private readonly string _rootPath;

   public TestController(IWebHostEnvironment env)
   {
      _rootPath = env.WebRootPath;
   }
}
MAYANK
  • 1