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.
The absolutePath function works by beginning at the starting folder and moving up one level for each "../" in the relative path. Then it concatenates the changed starting folder with the relative path to produce the equivalent absolute path.
In simple words, an absolute path refers to the same location in a file system relative to the root directory, whereas a relative path points to a specific location in a file system relative to the current directory you are working on.
path. relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path.
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.
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>
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