PageRenderTime 42ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/WCFWebApi/src/System.Net.Http/System/Net/Http/Headers/ByteArrayHeaderParser.cs

#
C# | 56 lines | 41 code | 9 blank | 6 comment | 5 complexity | 26401427e66293c271453f6bf5ecd7a5 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, Apache-2.0
  1. using System.Diagnostics.Contracts;
  2. namespace System.Net.Http.Headers
  3. {
  4. // Don't derive from BaseHeaderParser since parsing the Base64 string is delegated to Convert.FromBase64String()
  5. // which will remove leading, trailing, and whitespaces in the middle of the string.
  6. internal class ByteArrayHeaderParser : HttpHeaderParser
  7. {
  8. internal static readonly ByteArrayHeaderParser Parser = new ByteArrayHeaderParser();
  9. private ByteArrayHeaderParser()
  10. : base(false)
  11. {
  12. }
  13. public override string ToString(object value)
  14. {
  15. Contract.Assert(value is byte[]);
  16. return Convert.ToBase64String((byte[])value);
  17. }
  18. public override bool TryParseValue(string value, object storeValue, ref int index, out object parsedValue)
  19. {
  20. parsedValue = null;
  21. // Some headers support empty/null values. This one doesn't.
  22. if (string.IsNullOrEmpty(value) || (index == value.Length))
  23. {
  24. return false;
  25. }
  26. string base64String = value;
  27. if (index > 0)
  28. {
  29. base64String = value.Substring(index);
  30. }
  31. // Try convert the string (we assume it's a valid Base64 string) to byte[].
  32. try
  33. {
  34. // The RFC specifies that the MD5 should be a 128 bit digest. However, we don't validate the length and
  35. // let the user decide whether or not the byte[] is a valid Content-MD5 value or not.
  36. parsedValue = Convert.FromBase64String(base64String);
  37. index = value.Length;
  38. return true;
  39. }
  40. catch (FormatException e)
  41. {
  42. if (Logging.On) Logging.PrintError(Logging.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_parser_invalid_base64_string, base64String, e.Message));
  43. }
  44. return false;
  45. }
  46. }
  47. }