简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM