70

我正在尝试将我的旧 mvc5 项目移动到 asp net core。旧代码是:

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

错误是

当前上下文中不存在名称“MimeMapping”

在此处输入图像描述

4

3 回答 3

119

以下代码应该可以工作:

string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(FileName, out contentType);
return contentType ?? "application/octet-stream";
于 2016-03-09T00:24:03.817 回答
21

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

用法很简单:

string fileName = "trial.jpg";
string mime = MimeKit.MimeTypes.GetMimeType(fileName);
于 2016-09-28T17:50:25.293 回答
5

System.Web 没有迁移到 .NetCore,因为它过于依赖特定于平台的 API。您可以查看 Microsoft 参考源:

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

该代码受 MIT 许可证的约束。

于 2015-12-07T10:32:57.083 回答