Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ASP.NET Core determine MIME types and apply different middleware?

I use ASP.NET Core MVC and .NET Core 2.0.

I have some static files, they have different file types, JPEG, PNG, BMP ...

I would like to apply different middleware according to different file types.

Such as PNG file I will use ImageCompressMiddleware, BMP file I will use ImageConvertMiddleware.

How does ASP.NET Core determine MIME types and apply different middleware?

Or according to the file extension.

like image 491
Garfield550 Avatar asked Aug 28 '17 06:08

Garfield550


2 Answers

Create a FileExtensionContentTypeProvider object in configure section and fill or remove Mapping for each MIME Type as follows:

public void Configure(IApplicationBuilder app)
{
    // Set up custom content types -associating file extension to MIME type
    var provider = new FileExtensionContentTypeProvider();
    // Add new mappings
    provider.Mappings[".myapp"] = "application/x-msdownload";
    provider.Mappings[".htm3"] = "text/html";
    provider.Mappings[".image"] = "image/png";
    // Replace an existing mapping
    provider.Mappings[".rtf"] = "application/x-msdownload";
    // Remove MP4 videos.
    provider.Mappings.Remove(".mp4");

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

Go to this link for more information: microsoft

like image 154
Iman Bahrampour Avatar answered Oct 02 '22 12:10

Iman Bahrampour


The static files middleware basically has a very long list of explicit file extension to MIME type mappings. So the MIME type detection is solely based on the file extension.

There is not really a clear way to hook into the middleware after the MIME type has been detected but before the static files middleware actually runs. However, you can use the StaticFileOptions.OnPrepareResponse callback to hook into it to for example modify headers. Whether that’s enough for you depends on what you are trying to do.

If you want to do a more sophisticated handling, possibly replacing the static files middleware, you would need to run your own implementation of the MIME type detection.

like image 31
poke Avatar answered Oct 02 '22 13:10

poke