在ASP.NET 5中使用MimeMapping(vNext)

时间:2015-12-07 10:26:30

标签: c# asp.net-core-mvc mime-types system.web

我试图将旧的mvc5项目移至mvc6。 旧代码是:

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

错误是

  

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

enter image description here

3 个答案:

答案 0 :(得分:47)

以下代码应该有效:

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

答案 1 :(得分:11)

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

用法很简单:

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

答案 2 :(得分:2)

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

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

该代码须遵守MIT许可。