New helper will be available with .NET 11: MediaTypeMap.GetMediaType and MediaTypeMap.GetExtension which makes the web-development a bit easier!
MediaTypeMap.GetMediaType
The basic idea is that you get the MIME types from a given file or extension:
using System.Net.Mime;
_ = MediaTypeMap.GetMediaType("myfile.css"); // text/css
_ = MediaTypeMap.GetMediaType("resource.json"); // application/json
_ = MediaTypeMap.GetMediaType("rEsOuRCe.JsOn"); // application/json
_ = MediaTypeMap.GetMediaType("steven.giesel"); // null - as giesel is unfortunately not a wellknown extension
// It also works JUST with extensions or the whole path
_ = MediaTypeMap.GetMediaType("/home/user/myfile.css"); // text/css
_ = MediaTypeMap.GetMediaType("css"); // text/css
We can also "reverse-lookup" via:
MediaTypeMap.GetExtension
using System.Net.Mime;
_ = MediaTypeMap.GetExtension("application/pdf"); // ".pdf"
_ = MediaTypeMap.GetExtension("image/jpeg"); // ".jpg"
// Returns null for unknown ones
_ = MediaTypeMap.GetExtension("madeup/mimetype"); // null
_ = MediaTypeMap.GetExtension("/some/path/basic.css"); // null
It is also with a leading ".".
Resources:
- Issue on GitHub: https://github.com/dotnet/runtime/issues/121017
- Merged PR (if you want to have the full list): https://github.com/dotnet/runtime/pull/121776

