forked from nanoframework/Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ControllerPerson.cs
94 lines (87 loc) · 2.83 KB
/
ControllerPerson.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
//
// Copyright (c) 2020 Laurent Ellerbach and the project contributors
// See LICENSE file in the project root for full license information.
//
using System.Collections;
using System.Net;
using System.Text;
namespace nanoFramework.WebServer.Sample
{
public class Person
{
public string First { get; set; }
public string Last { get; set; }
}
public class ControllerPerson
{
private static ArrayList _persons = new ArrayList();
private static object _lock = new object();
[Route("Person")]
[Method("GET")]
public void Get(WebServerEventArgs e)
{
var ret = "[";
lock (_lock)
{
foreach (var person in _persons)
{
var per = (Person)person;
ret += $"{{\"First\"=\"{per.First}\",\"Last\"=\"{per.Last}\"}},";
}
}
if (ret.Length > 1)
{
ret = ret.Substring(0, ret.Length - 1);
}
ret += "]";
e.Context.Response.ContentType = "text/html";
e.Context.Response.ContentLength64 = ret.Length;
WebServer.OutPutStream(e.Context.Response, ret);
}
[Route("Person/Add")]
[Method("POST")]
public void AddPost(WebServerEventArgs e)
{
// Get the param from the body
byte[] buff = new byte[e.Context.Request.ContentLength64];
e.Context.Request.InputStream.Read(buff, 0, buff.Length);
string rawData = new string(Encoding.UTF8.GetChars(buff));
rawData = $"?{rawData}";
AddPerson(e.Context.Response, rawData);
}
[Route("Person/Add")]
[Method("GET")]
public void AddGet(WebServerEventArgs e)
{
AddPerson(e.Context.Response, e.Context.Request.RawUrl);
}
private void AddPerson(HttpListenerResponse response, string url)
{
var parameters = WebServer.DecodeParam(url);
Person person = new Person();
foreach (var param in parameters)
{
if (param.Name.ToLower() == "first")
{
person.First = param.Value;
}
else if (param.Name.ToLower() == "last")
{
person.Last = param.Value;
}
}
if ((person.Last != string.Empty) && (person.First != string.Empty))
{
lock (_lock)
{
_persons.Add(person);
}
WebServer.OutputHttpCode(response, HttpStatusCode.Accepted);
}
else
{
WebServer.OutputHttpCode(response, HttpStatusCode.BadRequest);
}
}
}
}