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