/
Cookie.cs
151 lines (135 loc) · 4.01 KB
/
Cookie.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
148
149
150
151
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace Microsoft.Http.Headers
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
public class Cookie // : Dictionary<string, string>
{
static readonly string AttributeOnly = Guid.NewGuid().ToString();
readonly Dictionary<string, string> dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
public Cookie()
{
}
public DateTime? Expires
{
get
{
if (!dict.ContainsKey("Expires"))
{
return null;
}
return HeaderFormatter.Default.FromString<DateTime>(dict["expires"]);
}
set
{
if (value == null)
{
dict.Remove("Expires");
}
else
{
dict["expires"] = HeaderFormatter.Default.ToString(value.Value);
}
}
}
public string Path
{
get
{
if (!dict.ContainsKey("path"))
{
return null;
}
return dict["path"];
}
set
{
dict["path"] = value;
}
}
public static Cookie Parse(string value)
{
var cookie = new Cookie();
foreach (var pair in HeaderStore.ParseMultiValue(value, ';'))
{
var eq = pair.IndexOf('=');
if (eq == -1)
{
cookie.Add(pair, Cookie.AttributeOnly);
continue;
}
cookie.Add(pair.Substring(0, eq).Trim(), pair.Substring(eq + 1).Trim());
}
return cookie;
}
public void Add(string key, string value)
{
dict.Add(key, value);
}
public void Add(string attributeName)
{
dict.Add(attributeName, Cookie.AttributeOnly);
}
// not there == exception, attribute = null, value = value
public string this[string key]
{
get
{
var v = dict[key];
if (v == AttributeOnly)
{
return null;
}
return v;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
dict[key] = value;
}
}
public bool HasAttribute(string key)
{
return ContainsKey(key) && this[key] == null;
}
public bool ContainsKey(string key)
{
return dict.ContainsKey(key);
}
public override string ToString()
{
if (dict.Count == 0)
{
return "";
}
StringBuilder sb = new StringBuilder();
foreach (var pair in dict)
{
if (string.IsNullOrEmpty(pair.Value))
{
continue;
}
if (sb.Length != 0)
{
sb.Append("; ");
}
if (pair.Value == Cookie.AttributeOnly)
{
sb.Append(pair.Key);
continue;
}
sb.AppendFormat("{0}={1}", pair.Key, pair.Value);
}
return sb.ToString();
}
}
}