I’m trying to serve images from a directory outside of the current ASP.NET Core 6 project that I’m working with and none of the images are showing. I’ve read the Docs and some of the other SO posts. So I kinda understand what needs to happen, I just don’t know if I’m doing this right.
Program.cs
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.GetFullPath("C:\Development\Website\Classic\websiteImages\Images\ItemImages")),
});
in the View I call the image like so
<img src="@Url.Content(@pic.FileLocation +"\"+ @pic.FileName)" />
and I’ve tried it this way as well
<img src="@[email protected]" alt="@pic.FileName" width="100" class="img-thumbnail d-inline">
This is the @pic.FileLocation
path: "C:DevelopmentWebsiteClassicwebsiteImagesImagesItemImages"
and @pic.FileName
is something coming from the Database like 10001234.jpg
If I copy and past the image path into a browser tab it shows the image, so I know the image is there.
Here is what the src
looks like in the browser.
3
Answers
What do you get for the img’s
src
attribute after the@Url.Content()
call? That is, what address is actually rendered to the browser as part of the final html?If the address still starts with
C:Development
, something isn’t right. The address in the image element’ssrc
attribute resolves from the perspective of the user’s browser, not your web server, so it needs to look something more like this:Then in your application, if the the classic site is no longer online on it’s own you need to able to receive a request for that address and map to the right place so it serves the right file.
You have to be careful testing this, because very often during development the server and browser run on the same computer. In that scenario, an address like
C:DevelopmentWebsite...
might seem to work just fine in the web browser, but it will fail as soon as you start hosting the application on it’s own server, away from the end user’s browser.Since you’ve already configured the statifiles middleware to provide files from that specific folder, this should work:
So as long as you generate URLs in this form:
~/{fileName}
you should be good.Here is the main documentation on serving files outside of the project folder structure:
Just remove
app.UseStaticFiles();
because you have alreadyapp.UseStaticFiles(new StaticFileOptions() ...
and then Try this:-Hope it will resolve your issue.