92

I'm trying to move my old mvc5 project to asp net core. Old code was:

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

Error is

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

enter image description here

Sauron
  • 2,156
  • 5
  • 17
  • 20

3 Answers3

150

The following code should work:

string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(FileName, out contentType);
return contentType ?? "application/octet-stream";
Mark G
  • 2,848
  • 1
  • 24
  • 32
  • 1
    @NickMuller is 'System.Net.Mime' supported in the netcore world? – Brennen Sprimont Oct 28 '16 at 15:31
  • 1
    @BrennenSprimont: Nope, it's not. Was working at a project targeting .NET 4.x, and I guess I got confused. I've deleted the comment, because I couldn't edit it anymore. – Nick Muller Oct 31 '16 at 10:31
  • 15
    note: In ASPNETCORE 2.1, this code requires adding Nuget Package: 'Microsoft.AspNetCore.StaticFiles', and 'using Microsoft.AspNetCore.StaticFiles;' declaration. – Sid James Jan 09 '19 at 02:06
  • Note: FileExtensionContentTypeProvider provides mimetype mapping for only a subset of mimetypes compared to MimeMapping.GetMimeMapping(). E.g. current visio types like .vsdx, .vsdm,... cannot be mapped with it! – MDummy Oct 05 '20 at 19:08
31

There is a NuGet package MimeTypes which works with .Net Core projects as an alternative to FileExtensionContentTypeProvider. I'm not aware of any other mime-type resolver package, which works with .Net Core (at least so far).

The usage is simple:

string fileName = "trial.jpg";
string mime = MimeKit.MimeTypes.GetMimeType(fileName);
Matyas
  • 1,122
  • 5
  • 23
  • 29
  • Simple = good ! First tried Mark's answer but you need to reference another dll. This approach just has a single purpose c# file that is added as a content file and is referenceable as shown. – Avner Nov 02 '20 at 01:07
  • 5
    With new version https://www.nuget.org/packages/MimeTypes , its just MimeTypes.GetMimeType(filename) – Tejasvi Hegde Sep 29 '21 at 09:30
  • Now that `Microsoft.AspNetCore.StaticFiles` is deprecated, this is a better solution. – HackSlash Jun 05 '23 at 18:26
7

System.Web is not moved to .NetCore because it relies too much on API's that are platform specific. You could take a look at Microsoft reference source:

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

The code is subject to a MIT license.

SynerCoder
  • 12,493
  • 4
  • 47
  • 78
  • After looking for alternate answers to that, there is none. The only better way would be to automatically generate C# code based on a static list. – Maxime Rouiller Dec 07 '15 at 15:53