ASP.Net Core: Serve All Static Files


Issue:

You need to serve a static file type in ASP.Net Core but that file type doesn't serve. ASP.Net Core does not by default serve static files. In order to do this you'll need to specifically tell it to do so like this as defined in the Configure method of Startup.cs.

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();
}	

The UseStaticFiles will serve over 400 types. There are instances though where file types you need to serve may still not exist. An example of this would be if Google, Bing or an SSL provider ask you to place a file on your web-site that has no extension (ASP.Net will not recongize this even with UseStaticFiles and thus won't serve it).

Solution:

There are a few options available to remedy this. The first allows you to setup specific file extensions mapped to mime types. The second opens it up all together (not recommended and a possible security risk but will work).

public void Configure(IApplicationBuilder app)
{
    // Set up custom content types and map them to a mime type.  You can setup
    // new types or re-map old ones.  You can additionally remove types you specifically
    // don't want to serve.
    var provider = new FileExtensionContentTypeProvider();
    // Add new mappings
    provider.Mappings[".jpg2"] = "image/jpeg";
    provider.Mappings[".htmlx"] = "text/html";

    // Remove MP4 videos.
    provider.Mappings.Remove(".mp4");

    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/Img"),
        ContentTypeProvider = provider
    });
}	

The below snippet though not recommend without good cause will open up any file for serving.

    app.UseStaticFiles(new StaticFileOptions()
    {
        ServeUnknownFileTypes = true
    });

Finally, if this is something you feel you may want in your toolbox in the future you can always make a handy extension method to wrap it's functionality. I have a shared utility library where I put this kind of stuff. Here is an extension method to extend the IApplicationBuilder to add the additional "UseAllStaticFiles" method.

    public static void UseAllStaticFiles(this IApplicationBuilder app)
    {
        app.UseStaticFiles(new StaticFileOptions()
        {
            ServeUnknownFileTypes = true
        });
    }

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.