Using MimeMapping in ASP.NET Core

35,163

Solution 1

The following code should work:

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

Solution 2

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);

Solution 3

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.

Share:
35,163
Sauron
Author by

Sauron

Updated on July 05, 2022

Comments

  • Sauron
    Sauron almost 2 years

    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

  • Maxime Rouiller
    Maxime Rouiller over 8 years
    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.
  • Brennen Sprimont
    Brennen Sprimont over 7 years
    @NickMuller is 'System.Net.Mime' supported in the netcore world?
  • Nicky Muller
    Nicky Muller over 7 years
    @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.
  • Sid James
    Sid James over 5 years
    note: In ASPNETCORE 2.1, this code requires adding Nuget Package: 'Microsoft.AspNetCore.StaticFiles', and 'using Microsoft.AspNetCore.StaticFiles;' declaration.
  • MDummy
    MDummy over 3 years
    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!
  • Avner
    Avner over 3 years
    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.
  • Tejasvi Hegde
    Tejasvi Hegde over 2 years
    With new version nuget.org/packages/MimeTypes , its just MimeTypes.GetMimeType(filename)