101

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

3 Answers 3

166

The following code should work:

string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(FileName, out contentType);
return contentType ?? "application/octet-stream";
Sign up to request clarification or add additional context in comments.

4 Comments

@NickMuller is 'System.Net.Mime' supported in the netcore world?
@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.
note: In ASPNETCORE 2.1, this code requires adding Nuget Package: 'Microsoft.AspNetCore.StaticFiles', and 'using Microsoft.AspNetCore.StaticFiles;' declaration.
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!
37

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

3 Comments

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.
With new version nuget.org/packages/MimeTypes , its just MimeTypes.GetMimeType(filename)
Now that Microsoft.AspNetCore.StaticFiles is deprecated, this is a better solution.
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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.