This repository was archived by the owner on Nov 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHttpHandler.cs
More file actions
345 lines (282 loc) · 13.3 KB
/
HttpHandler.cs
File metadata and controls
345 lines (282 loc) · 13.3 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
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using System.Web.Helpers;
using System.Web.Routing;
using TinyWebStack.Extensions;
namespace TinyWebStack
{
public class HttpHandler : HttpTaskAsyncHandler
{
private static readonly DateTime DeleteCookieDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public HttpHandler(Type handlerType, RouteData routeData)
{
this.HandlerType = handlerType;
this.RouteData = routeData;
}
private Type HandlerType { get; set; }
private RouteData RouteData { get; set; }
public override Task ProcessRequestAsync(HttpContext http)
{
//var status = await this.GetStatusAsync(http);
//http.Response.StatusCode = status.Code;
//http.Response.StatusDescription = status.Description;
//http.Response.RedirectLocation = http.Request.ResolveUrl(status.Location);
//http.Response.TrySkipIisCustomErrors = true;
return this.GetStatusAsync(http)
.ContinueWith(status =>
{
http.Response.StatusCode = status.Result.Code;
http.Response.StatusDescription = status.Result.Description;
http.Response.RedirectLocation = http.Request.ResolveUrl(status.Result.Location);
http.Response.TrySkipIisCustomErrors = true;
});
}
private Task<Status> GetStatusAsync(HttpContext http)
{
// Look for a handler method named the standard "async" way (i.e. GetAsync or PostAsync) and if that isn't
// found, look for a plainly named handler method (i.e. Get or Post).
//
var handlerMethod = this.HandlerType.GetMethod(http.Request.HttpMethod + "Async", BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase);
if (handlerMethod == null)
{
handlerMethod = this.HandlerType.GetMethod(http.Request.HttpMethod, BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase);
}
if (handlerMethod == null)
{
return Task.FromResult<Status>(Status.MethodNotAllowed);
}
var handler = this.CreateInstanceWithResolution(this.HandlerType);
if (handler == null)
{
return Task.FromResult<Status>(Status.InternalServerError);
}
var handlerProperties = this.HandlerType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy).ToList();
// Assign query string/route data to the handler and query string objects.
//
var queryStringObjects = handlerMethod.GetParameters().Select(param => Activator.CreateInstance(param.ParameterType)).ToArray();
var queryString = http.Request.Unvalidated().QueryString;
var queryStringData = PopulateDictionary(queryString, this.RouteData.Values);
if (queryString.Count > 0)
{
queryStringData["_RawQueryString"] = queryString.ToString().UrlDecode();
}
this.AssignInputs(queryStringData, handler, handlerProperties.Where(p => p.GetSetMethod() != null && !p.Name.Equals("Input") && !(p.Equals("Output"))));
foreach (var queryStringObject in queryStringObjects)
{
this.AssignInputs(queryStringData, queryStringObject, null);
}
// If there is an input property, assign it.
//
var inputDataProperty = handlerProperties.Where(p => p.GetSetMethod() != null && p.Name.Equals("Input")).FirstOrDefault();
if (inputDataProperty != null)
{
var contentType = http.Request.ContentType;
if (contentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
{
var inputObject = Activator.CreateInstance(inputDataProperty.PropertyType);
// TODO: check the incoming content type and do not assume it's always POSTed form data.
var formData = PopulateDictionary(http.Request.Unvalidated().Form);
this.AssignInputs(formData, inputObject, null);
inputDataProperty.SetValue(handler, inputObject, null);
}
else if (contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
var json = http.Request.Unvalidated().Form;
if (inputDataProperty.PropertyType == typeof(string))
{
inputDataProperty.SetValue(handler, json, null);
}
else
{
throw new NotImplementedException("Do not currently suport serializing objects from JSON");
}
}
//else
//{
// throw new NotImplementedException(String.Concat("Unsupported request content type: ", contentType));
//}
}
// Get cookie properties and assign any cookies from the request.
//
var cookieProperties = this.GetCookieProperties(handlerProperties).ToList();
this.ReadCookies(http.Request.Cookies, handler, cookieProperties);
// If there is an output and the output is requested, find a content writer.
//
var outputDataProperty = handlerProperties.Where(p => p.GetGetMethod() != null && p.Name.Equals("Output")).FirstOrDefault();
IContentTypeWriter writer = null;
if (outputDataProperty != null && !"HEAD".Equals(http.Request.HttpMethod, StringComparison.OrdinalIgnoreCase))
{
if (!ContentHandling.TryGetContentTypeWriter(http.Request.AcceptTypes, this.HandlerType, outputDataProperty.PropertyType, out writer))
{
return Task.FromResult<Status>(Status.NotAcceptable);
}
}
// Execute the method to retrieve the status.
//
Task<Status> statusTask;
if (handlerMethod.ReturnType.IsAssignableFrom(typeof(Task<Status>)))
{
statusTask = (Task<Status>)handlerMethod.Invoke(handler, queryStringObjects);
}
else
{
statusTask = Task.FromResult<Status>((Status)handlerMethod.Invoke(handler, queryStringObjects));
}
var outputData = (outputDataProperty != null) ? outputDataProperty.GetValue(handler, null) : null;
if (writer != null && outputData != null)
{
writer.Write(http.Response.Output, outputData);
http.Response.ContentType = writer.ContentType;
}
// Write cookies back to the response.
//
this.WriteCookies(http.Response.Cookies, handler, cookieProperties);
return statusTask;
}
private object CreateInstanceWithResolution(Type type)
{
var success = false;
object[] arguments = null;
// Find the most complex constructor (the one with the most parameters) for which we can resolve via the
// IOC container.
//
foreach (var constructor in type.GetConstructors().OrderByDescending(c => c.GetParameters().Length))
{
var parameters = constructor.GetParameters();
arguments = new object[parameters.Length];
try
{
for (var i = 0; i < arguments.Length; ++i)
{
arguments[i] = Container.Current.Resolve(parameters[i].ParameterType);
}
success = true;
break;
}
catch (KeyNotFoundException)
{
}
}
return success ? Activator.CreateInstance(type, arguments) : null;
}
private IDictionary<string, object> PopulateDictionary(params object[] collections)
{
var inputs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var collection in collections)
{
var nvc = collection as NameValueCollection;
if (nvc != null)
{
foreach (string key in nvc.Keys)
{
inputs[key ?? "_UnnamedQueryStringValue"] = nvc.GetValues(key);
}
}
else
{
var dictionary = collection as IDictionary<string, object>;
foreach (var kvp in dictionary)
{
inputs[kvp.Key] = kvp.Value;
}
}
}
return inputs;
}
private void AssignInputs(IDictionary<string, object> inputs, object target, IEnumerable<PropertyInfo> properties)
{
foreach (var property in properties ?? target.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy).Where(p => p.GetSetMethod() != null))
{
if (property.PropertyType.IsInterface)
{
try
{
var resolved = Container.Current.Resolve(property.PropertyType);
property.SetValue(target, resolved, null);
}
catch (KeyNotFoundException)
{
// TODO: should we rethrow here since it indicates the interface was not registered with the container?
}
}
else
{
object value;
if (inputs.TryGetValue(property.Name, out value))
{
if (value != null)
{
var valueType = value.GetType();
if (!property.PropertyType.IsArray && valueType.IsArray)
{
value = ((Array)value).GetValue(0);
}
}
var assign = Convert.ChangeType(value, property.PropertyType);
property.SetValue(target, assign, null);
}
}
}
}
private IEnumerable<CookiedProperty> GetCookieProperties(IEnumerable<PropertyInfo> properties)
{
foreach (var property in properties)
{
foreach (var attribute in property.GetCustomAttributes(typeof(CookieAttribute), false).Cast<CookieAttribute>())
{
yield return new CookiedProperty() { Property = property, Attribute = attribute };
}
}
}
private void ReadCookies(HttpCookieCollection cookies, object target, IEnumerable<CookiedProperty> cookiedProperties)
{
foreach (var cookiedProperty in cookiedProperties.Where(p => p.Property.GetSetMethod() != null))
{
var cookie = cookies[cookiedProperty.Attribute.Name];
if (cookie != null)
{
object value = (cookie.Values.Count > 1) ? cookie[cookiedProperty.Property.Name] : cookie.Value;
var assign = Convert.ChangeType(value, cookiedProperty.Property.PropertyType);
cookiedProperty.Property.SetValue(target, assign, null);
}
}
}
private void WriteCookies(HttpCookieCollection cookies, object target, IEnumerable<CookiedProperty> cookiedProperties)
{
foreach (var cookiedProperty in cookiedProperties.Where(p => p.Property.GetGetMethod() != null))
{
var cookie = new HttpCookie(cookiedProperty.Attribute.Name);
cookies.Add(cookie);
var value = cookiedProperty.Property.GetValue(target, null);
if (value == null)
{
cookie.Expires = HttpHandler.DeleteCookieDate;
}
else
{
cookie.Value = value.ToString();
cookie.HttpOnly = cookiedProperty.Attribute.HttpOnly;
cookie.Secure = cookiedProperty.Attribute.Secure;
if (cookiedProperty.Attribute.Expires > 0)
{
cookie.Expires = DateTime.UtcNow.AddMinutes(cookiedProperty.Attribute.Expires);
}
if (!String.IsNullOrEmpty(cookiedProperty.Attribute.Path))
{
cookie.Path = cookiedProperty.Attribute.Path;
}
}
}
}
private class CookiedProperty
{
public PropertyInfo Property { get; set; }
public CookieAttribute Attribute { get; set; }
}
}
}