C# 在ASP.NET内核中使用MimeMapping

C# 在ASP.NET内核中使用MimeMapping,c#,asp.net-core-mvc,mime-types,system.web,C#,Asp.net Core Mvc,Mime Types,System.web,我正在尝试将旧的mvc5项目迁移到asp net核心。 旧代码是: public string ContentType { get { if (!string.IsNullOrEmpty(FileName)) return MimeMapping.GetMimeMapping(FileName); return null; } } 错误是 当前上下文中不存在名称“MimeMapping” System.Web未移动

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

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

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


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


该代码受麻省理工学院许可证的约束。

以下代码应该可以工作:

string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(FileName, out contentType);
return contentType ?? "application/octet-stream";
有一个NuGet包,它可以与.Net核心项目一起工作,作为
FileExtensionContentTypeProvider
的替代方案。我不知道还有任何其他mime类型的解析器包,它可以与.NETCore一起工作(至少到目前为止)

用法很简单:

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

在寻找其他答案之后,没有答案。唯一更好的方法是根据静态列表自动生成C#代码。@NickMuller在netcore世界中支持“System.Net.Mime”?@BrennenSprimont:不,不支持。在一个以.NET4.x为目标的项目中工作,我想我被搞糊涂了。我已删除注释,因为我无法再编辑它。注意:在ASPNETCORE 2.1中,此代码需要添加Nuget软件包:“Microsoft.ASPNETCORE.StaticFiles”和“使用Microsoft.ASPNETCORE.StaticFiles;”声明.注意:FileExtensionContentTypeProvider仅为mimetype的子集提供mimetype映射,而不是MimeMapping.GetMIMEMEMApping()。例如,当前的visio类型,如.vsdx、.vsdm、,。。。不能用它来映射!简单=好!首先尝试了Mark的答案,但您需要引用另一个dll。这种方法只有一个单一用途的c#文件,该文件作为内容文件添加,并且可以引用,如图所示。