在 ASP.NET Core 中使用 MimeMapping

问题描述 投票:0回答:3

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

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

错误是

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

c# asp.net-core-mvc mime-types system.web
3个回答
151
投票

以下代码应该可以工作:

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

32
投票

有一个 NuGet 包 MimeTypes,它可以与 .Net Core 项目一起使用,作为

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

使用方法很简单:

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

7
投票

System.Web 没有迁移到 .NetCore,因为它过于依赖特定于平台的 API。你可以看一下微软的参考资料:

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

该代码受 MIT 许可证约束。

© www.soinside.com 2019 - 2024. All rights reserved.