Virtual directory inside of ASP.NET Core app in IIS

I have found a blog which I think must have been written by the OP.

The upshot is not to use a virtual directory in IIS at all but rather map your path in Startup.cs to the physical server directory. I hope the OP does not mind that I have pasted the blog below, but it helped me when I first encountered this problem today.

Source: https://www.jauernig-it.de/asp-net-coreiis-serving-content-from-a-file-share/

There are situations, when you want to serve static content with your application, that is not part of it, e.g. because it exists on a common file share. Website content, that is managed by a business division, could be such a use case. In ASP.NET before Core, this was no problem in IIS: just create a virtual directory within your IIS website and point it to the file share.

Unfortunately, with ASP.NET Core, this approach isn’t working any longer. If you add a virtual directory to your ASP.NET Core application in IIS, it isn’t recognized and a 404 is returned. It’s because of DNX/Kestrel, which is running beneath IIS (using the HttpPlatformHandler module) and to which IIS only brokers the requests. Kestrel doesn’t know anything of virtual directories from IIS. And because ASP.NET Core applications are independent from IIS and could also be run without it (e.g. running Kestrel standalone), that should be considered as a good thing.

But now we need another solution for our problem… fortunately, ASP.NET Core gives us a programmatic interface to serve files from anywhere. Just add the following code to your Startup.cs Configure() method:

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

What this essentially does, is adding a file server to a physical server path, that is then available on a certain request path, in this case with directory browsing disabled. You are also able to serve from a path relative to your application, using new PhysicalFileProvider(env.WebRootPath + “\path”) (given env is of type IHostingEnvironment as parameter of Configure()). Voila, that’s it. There is no need to add a „virtual directory“ in IIS, this stuff is deprecated and a thing of the past. For me, this is a good thing, because we get more independent of the whole IIS…

Leave a Comment