Using MimeMapping in ASP.NET Core

C#asp.net Core-MvcMime Typessystem.web

C# Problem Overview


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

C# Solutions


Solution 1 - C#

The following code should work:

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

Solution 2 - C#

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 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSauronView Question on Stackoverflow
Solution 1 - C#Mark GView Answer on Stackoverflow
Solution 2 - C#MatyasView Answer on Stackoverflow
Solution 3 - C#SynerCoderView Answer on Stackoverflow