如何在ASP.NET Core中添加Mime类型

16

在使用.NET Framework 4.6(MVC4/5)开发应用程序时,我过去常常需要在web.config文件中添加自定义mime类型,例如(这是我需要在应用程序中添加的实际mime类型):

<system.webServer>
  <staticContent>
    <mimeMap fileExtension=".wasm" mimeType="application/wasm"/>
    <mimeMap fileExtension="xap" mimeType="application/x-silverlight-app"/>
    <mimeMap fileExtension="xaml" mimeType="application/xaml+xml"/>
    <mimeMap fileExtension="xbap" mimeType="application/x-ms-xbap"/>
  </staticContent>

在.NET Core中如何复制这种行为?是否可以以相同的方式实现?


请参阅:https://learn.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.staticfiles.fileextensioncontenttypeprovider.trygetcontenttype?view=aspnetcore-2.1#Microsoft_AspNetCore_StaticFiles_FileExtensionContentTypeProvider_TryGetContentType_System_String_System_String__ - Dan Wilson
在IIS后面,您可以以相同的方式做到这一点,但不要忘记在启动类的Configure方法中添加UseStaticFiles - agua from mars
@DanWilson 我已经阅读了文档,但它没有解释如何实现它。 - Rambo3
我的ASP.NET Core MVC应用程序没有web.config文件。我应该在哪里进行配置? - Chris G. Williams
ASP.Net Core中的映射细节 - Iman Bahrampour
2个回答

29

这个配置是为了 Web 服务器而不是 ASP.NET。web.config 中的 system.webServer 部分处理 IIS 的配置。

如果您的 ASP.NET Core 应用程序在 IIS 后面运行,而且 IIS 处理静态内容,则应继续使用相同的东西。

如果您使用 nginx,则可以将 MIME 类型添加到您的配置中或编辑 mime.types 文件。如果您使用其他 Web 服务器,请参阅该 Web 服务器的文档。

如果 ASP.NET Core 自己处理静态内容并且运行在边缘上,或者如果您需要 ASP.NET Core 知道 MIME 类型,则需要配置 ASP.NET Core 的处理程序知道它。这在 文档 中有说明。

文档中的示例:

public void Configure(IApplicationBuilder app)
{
    var provider = new FileExtensionContentTypeProvider();
    // Add new mappings
    provider.Mappings[".myapp"] = "application/x-msdownload";

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

0
对于ASP.NET Core应用程序,IIS的更改不起作用。
在您的Startup.cs文件的Configure方法中,进行以下更改:
app.UseStaticFiles(new StaticFileOptions()
            {
                ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
  {
    { ".apk","application/vnd.android.package-archive"}
  })
            });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接