在 ASP.NET 核心中使用 MimeMapping

Using MimeMapping in ASP.NET Core

我正在尝试将我的旧 mvc5 项目移动到 asp 网络核心。 旧代码是:

public string ContentType
{
    get
    {
        if (!string.IsNullOrEmpty(FileName))
            return MimeMapping.GetMimeMapping(FileName);
        return null;
    }
}

错误是

The name 'MimeMapping' does not exist in the current context

System.Web 未移至 .NetCore,因为它过于依赖特定于平台的 API。你可以看看微软的参考资料来源:

https://github.com/Microsoft/referencesource/blob/master/System.Web/MimeMapping.cs

代码受 MIT 许可约束。

以下代码应该有效:

string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(FileName, out contentType);
return contentType ?? "application/octet-stream";

有一个 NuGet 包 MimeTypes 可以作为 FileExtensionContentTypeProvider 的替代品与 .Net Core 项目一起使用。我不知道任何其他 mime 类型的解析器包,它适用于 .Net Core(至少到目前为止)。

用法很简单:

string fileName = "trial.jpg";
string mime = MimeKit.MimeTypes.GetMimeType(fileName);