Using MimeMapping in ASP.NET Core
Asked Answered
G

3

95

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

Goble answered 7/12, 2015 at 10:26 Comment(0)
C
155

The following code should work:

string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(FileName, out contentType);
return contentType ?? "application/octet-stream";
Consternation answered 9/3, 2016 at 0:24 Comment(4)
@NickMuller is 'System.Net.Mime' supported in the netcore world?Hartzel
@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.Culmination
note: In ASPNETCORE 2.1, this code requires adding Nuget Package: 'Microsoft.AspNetCore.StaticFiles', and 'using Microsoft.AspNetCore.StaticFiles;' declaration.Glenoid
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!Protective
D
33

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);
Daisy answered 28/9, 2016 at 17:50 Comment(3)
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.Plug
With new version nuget.org/packages/MimeTypes , its just MimeTypes.GetMimeType(filename)Repulsive
Now that Microsoft.AspNetCore.StaticFiles is deprecated, this is a better solution.Steven
G
6

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.

Gruel answered 7/12, 2015 at 10:32 Comment(1)
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.Reach

© 2022 - 2024 — McMap. All rights reserved.