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

十年热恋 提交于 2021-02-07 14:21:51

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/45913273/how-does-asp-net-core-determine-mime-types-and-apply-different-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!