-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequest.cs
More file actions
67 lines (66 loc) · 2.38 KB
/
Request.cs
File metadata and controls
67 lines (66 loc) · 2.38 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
using System.IO;
using System.Collections.Specialized;
using static System.Web.HttpUtility;
namespace Webtech3;
/// <summary>
/// Struct with Request data and some useful methods.
/// Hides unnecessary info
/// </summary>
public struct Request(HttpListenerRequest request) {
readonly HttpListenerRequest req = request;
/// <summary>
/// Property with HTTP Method
/// </summary>
/// <value>HTTP.Methods enum instance</value>
public readonly HTTP.Methods Method { get => req.HttpMethod.ToHTTPMethod(); }
/// <summary>
/// Property with headers data from request
/// </summary>
/// <value>NameValueCollection obj</value>
public readonly NameValueCollection Headers { get => req.Headers; }
/// <summary>
/// Property for getting url path (after address & before query)
/// </summary>
/// <value>String with path</value>
public readonly string Url { get => req.Url!.AbsolutePath; }
/// <summary>
/// Property with request's cookies
/// </summary>
/// <value>CookieCollection obj</value>
public readonly CookieCollection Cookies { get => req.Cookies; }
/// <summary>
/// Property for getting request's body
/// </summary>
/// <value>Stream with content</value>
public readonly Stream Body { get => req.InputStream; }
/// <summary>
/// Property with authentificated user, if auth is enabled
/// </summary>
/// <value>User or null</value>
public User? CurrentUser { get; internal set; }
private static Dictionary<string, string> Parse(string data) => new(
from par in data.TrimStart('?').Split('&')
let buff = par.Split('=')
select new KeyValuePair<string, string>(
UrlDecode(buff[0]), UrlDecode(buff[1])
)
);
/// <summary>
/// Property for getting parsed as dict query
/// </summary>
/// <value>Dict<str, str> with data</value>
public readonly Dictionary<string, string> Query {
get => Parse(req.Url!.Query);
}
/// <summary>
/// Async parse the form data from body to dict
/// </summary>
/// <returns>Dict<str, str> with form data</returns>
public async readonly Task<Dictionary<string, string>> ParseForm() {
string form;
using(var input = new StreamReader(req.InputStream, req.ContentEncoding)) {
form = await input.ReadToEndAsync();
}
return Parse(form);
}
}