-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Net
Milestone
Description
Background and motivation
It's reasonably common to need to get a MIME / media type for a file extension, or vice versa. The core .NET libraries don't include any exposed mapping, so developers end up needing to re-create the subset of the mapping that's relevant to their current needs. Java supports this with URLConnection.getFileNameMap, Go supports this with its built-in mime.TypeByExtension, Swift has UTType... .NET should have this available as well. It would support all IANA mappings plus very common ones like those from Apache mime.types or mime-db.
API Proposal
namespace System.Net.Mime; // existing namespace for MediaTypeNames
public static class MediaTypeMap // members could alternatively be added to MediaTypeNames if we wanted to avoid the extra type
{
public static bool TryGetMediaType(ReadOnlySpan<char> extension, [NotNullWhen(true)] out string? mediaType);
public static bool TryGetExtension(ReadOnlySpan<char> mediaType, [NotNullWhen(true)] out string? extension);
}API Usage
UriContent image = new(uri, MediaTypeMap.TryGetMediaType(Path.GetExtension(uri.AbsolutePath), out var mediaType) ? mediaType : "image/*"));Alternative Designs
namespace System.Net.Mime; // existing namespace for MediaTypeNames
public static class MediaTypeMap // members could alternatively be added to MediaTypeNames if we wanted to avoid the extra type
{
public static string? GetMediaType(ReadOnlySpan<char> extension);
public static string? GetExtension(ReadOnlySpan<char> mediaType);
}namespace System.Net.Mime; // existing namespace for MediaTypeNames
public static class MediaTypeMap // members could alternatively be added to MediaTypeNames if we wanted to avoid the extra type
{
// optional, on top of the functions
public static IReadOnlyDictionary<string, string> MediaTypeToExtension { get; }
public static IReadOnlyDictionary<string, string> ExtensionToMediaType { get; }
}Risks
- We may not be "complete" in the opinion of some consumers and may have a trickle of requests for adding new entries. Those new entries would not require public API, though; they'd just be updating the internal map.
EDIT: updated after internal discussion
DL444, liveans, nil4, EgorBo, pedoc and 7 more
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Net