| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | #nullable disable |
| | 5 | |
|
| | 6 | | using System; |
| | 7 | | using System.Text; |
| | 8 | |
|
| | 9 | | namespace Azure.Core.Pipeline |
| | 10 | | { |
| | 11 | | internal static class ContentTypeUtilities |
| | 12 | | { |
| | 13 | | public static bool TryGetTextEncoding(string contentType, out Encoding encoding) |
| | 14 | | { |
| | 15 | | const string charsetMarker = "; charset="; |
| | 16 | | const string utf8Charset = "utf-8"; |
| | 17 | | const string textContentTypePrefix = "text/"; |
| | 18 | | const string jsonSuffix = "json"; |
| | 19 | | const string appJsonPrefix = "application/json"; |
| | 20 | | const string xmlSuffix = "xml"; |
| | 21 | | const string urlEncodedSuffix = "-urlencoded"; |
| | 22 | |
|
| | 23 | | // Default is technically US-ASCII, but will default to UTF-8 which is a superset. |
| | 24 | | const string appFormUrlEncoded = "application/x-www-form-urlencoded"; |
| | 25 | |
|
| 60 | 26 | | if (contentType == null) |
| | 27 | | { |
| 8 | 28 | | encoding = null; |
| 8 | 29 | | return false; |
| | 30 | | } |
| | 31 | |
|
| 52 | 32 | | var charsetIndex = contentType.IndexOf(charsetMarker, StringComparison.OrdinalIgnoreCase); |
| 52 | 33 | | if (charsetIndex != -1) |
| | 34 | | { |
| 52 | 35 | | ReadOnlySpan<char> charset = contentType.AsSpan().Slice(charsetIndex + charsetMarker.Length); |
| 52 | 36 | | if (charset.StartsWith(utf8Charset.AsSpan(), StringComparison.OrdinalIgnoreCase)) |
| | 37 | | { |
| 52 | 38 | | encoding = Encoding.UTF8; |
| 52 | 39 | | return true; |
| | 40 | | } |
| | 41 | | } |
| | 42 | |
|
| 0 | 43 | | if (contentType.StartsWith(textContentTypePrefix, StringComparison.OrdinalIgnoreCase) || |
| 0 | 44 | | contentType.EndsWith(jsonSuffix, StringComparison.OrdinalIgnoreCase) || |
| 0 | 45 | | contentType.EndsWith(xmlSuffix, StringComparison.OrdinalIgnoreCase) || |
| 0 | 46 | | contentType.EndsWith(urlEncodedSuffix, StringComparison.OrdinalIgnoreCase) || |
| 0 | 47 | | contentType.StartsWith(appJsonPrefix, StringComparison.OrdinalIgnoreCase) || |
| 0 | 48 | | contentType.StartsWith(appFormUrlEncoded, StringComparison.OrdinalIgnoreCase)) |
| | 49 | | { |
| 0 | 50 | | encoding = Encoding.UTF8; |
| 0 | 51 | | return true; |
| | 52 | | } |
| | 53 | |
|
| 0 | 54 | | encoding = null; |
| 0 | 55 | | return false; |
| | 56 | | } |
| | 57 | | } |
| | 58 | | } |