forked from bonesoul/uhttpsharp
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathIHttpContext.cs
More file actions
109 lines (81 loc) · 2.49 KB
/
IHttpContext.cs
File metadata and controls
109 lines (81 loc) · 2.49 KB
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
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using uhttpsharp.Headers;
namespace uhttpsharp
{
public interface IHttpContext
{
IHttpRequest Request { get; }
IHttpResponse Response { get; set; }
ICookiesStorage Cookies { get; }
dynamic State { get; }
EndPoint RemoteEndPoint { get; }
}
public interface ICookiesStorage : IHttpHeaders
{
void Upsert(string key, string value);
void Remove(string key);
bool Touched { get; }
string ToCookieData();
}
public class CookiesStorage : ICookiesStorage
{
private static readonly string[] CookieSeparators = { "; ", "=" };
private readonly Dictionary<string, string> _values;
private bool _touched;
public bool Touched
{
get { return _touched; }
}
public string ToCookieData()
{
StringBuilder builder = new StringBuilder();
foreach (var kvp in _values)
{
builder.AppendFormat("Set-Cookie: {0}={1}{2}", kvp.Key, kvp.Value, Environment.NewLine);
}
return builder.ToString();
}
public CookiesStorage(string cookie)
{
var keyValues = cookie.Split(CookieSeparators, StringSplitOptions.RemoveEmptyEntries);
_values = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
for (int i = 0; i < keyValues.Length; i += 2)
{
var key = keyValues[i];
var value = keyValues[i + 1];
_values[key] = value;
}
}
public void Upsert(string key, string value)
{
_values[key] = value;
_touched = true;
}
public void Remove(string key)
{
if (_values.Remove(key))
{
_touched = true;
}
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
return _values.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public string GetByName(string name)
{
return _values[name];
}
public bool TryGetByName(string name, out string value)
{
return _values.TryGetValue(name, out value);
}
}
}