Search code examples
c#htmlasp.netiisvirtual-directory

How to display images stored in a virtual directory in .NET Core app?


I want to display images on my .net core website. The images are stored outside of the website-folder on an IIS server.

On the internet, I read that one way to go about doing so, is using a virtual directory which I then set up. Below the configuration of the virtual directory:

Configuration of the virtual directory

I thought, it would be easy to access pictures saved inside of the folder, the virtual directory points to, but I've not succeeded until now.

In my html, I tried the following:

<img src="/Uploads/image.jpg" />

and

<img src="Uploads/image.jpg" />

and

<img src="../Uploads/image.jpg" />

and

<img src="./Uploads/image.jpg" />

but nothing worked. When inspecting the website, there's an 404 error for the image.

Update: I added permissions to the virtual directory (full access) for IUSR and IIS_IUSRS

Update: So it seems as if I cannot access virtual directories from a .net core web app as per this blog post: https://www.jauernig-it.de/asp-net-coreiis-serving-content-from-a-file-share/

Instead, the author advises to use UseFileServer() in Startup.cs. I'm, however, not sure yet how to upload images into the file server and display them.


Solution

  • So it turns out you cannot use virtual directories in ASP.NET Core web applications (as per this blog post, for instance: https://www.jauernig-it.de/asp-net-coreiis-serving-content-from-a-file-share/ ). Instead of configuring a virtual directory pointing to a certain folder on your server, you have to add the following code to your Configure() in Startup.cs:

    app.UseFileServer(new FileServerOptions
    {
    FileProvider = new PhysicalFileProvider(@"\\server\path"),
    RequestPath = new PathString("/MyPath"),
    EnableDirectoryBrowsing = false
    });
    

    If the the path would, for example point to a folder containg the image image.jpg, you could use the image from your code like this:

    <img src="/MyPath/image.jpg" />