forked from dotnet/systemweb-adapters
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpValueCollection.cs
147 lines (117 loc) · 3.43 KB
/
HttpValueCollection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Web;
namespace Microsoft.AspNetCore.SystemWebAdapters.Internal;
internal class HttpValueCollection : NameValueCollection
{
internal HttpValueCollection(string? str = null, Encoding? encoding = null)
: base(StringComparer.OrdinalIgnoreCase)
{
if (!string.IsNullOrEmpty(str))
{
FillFromString(str, true, encoding);
}
IsReadOnly = false;
}
internal void FillFromString(string s, bool urlencoded = false, Encoding? encoding = null)
{
var i = 0;
while (i < s.Length)
{
// find next & while noting first = on the way (and if there are more)
var si = i;
var ti = -1;
while (i < s.Length)
{
var ch = s[i];
if (ch == '=')
{
if (ti < 0)
ti = i;
}
else if (ch == '&')
{
break;
}
i++;
}
// extract the name / value pair
string? name = null;
string? value;
if (ti >= 0)
{
name = s[si..ti];
value = s.Substring(ti + 1, i - ti - 1);
}
else
{
value = s[si..i];
}
// add name / value pair to the collection
if (urlencoded)
{
var (decodedName, decodedValue) = encoding is null
? (HttpUtility.UrlDecode(name), HttpUtility.UrlDecode(value))
: (HttpUtility.UrlDecode(name, encoding), HttpUtility.UrlDecode(value, encoding));
base.Add(decodedName, decodedValue);
}
else
{
base.Add(name, value);
}
// trailing '&'
if (i == s.Length - 1 && s[i] == '&')
{
base.Add(null, string.Empty);
}
i++;
}
}
public override string ToString() => ToString(true);
internal string ToString(bool urlencoded)
{
int count = Count;
if (count == 0)
{
return string.Empty;
}
var s = new StringBuilder();
foreach (string k in this)
{
var key = k;
if (urlencoded)
{
key = HttpUtility.UrlEncode(key);
}
var keyPrefix = string.IsNullOrEmpty(key) ? string.Empty : $"{key}=";
var values = GetValues(k);
if (s.Length > 0)
{
s.Append('&');
}
if (values is null)
{
continue;
}
for (var j = 0; j < values.Length; j++)
{
if (j > 0)
{
s.Append('&');
}
s.Append(keyPrefix);
var item = (string?)values[j];
if (urlencoded)
{
item = HttpUtility.UrlEncode(item);
}
s.Append(item);
}
}
return s.ToString();
}
}