-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.Static.cs
More file actions
399 lines (327 loc) · 13.9 KB
/
Copy pathAPI.Static.cs
File metadata and controls
399 lines (327 loc) · 13.9 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
using Microsoft.AspNetCore.Http;
using System.Collections.Specialized;
using System.Globalization;
using System.Net;
using System.Net.Mime;
using System.Reflection;
using System.Text.RegularExpressions;
namespace API
{
/// <summary>
/// Static implementation
/// </summary>
public class Static : Common
{
#region Properties
/// <summary>
/// List of URL Request Parameters
/// </summary>
private List<string> RequestParams = new List<string>();
/// <summary>
/// allowed http methods
/// </summary>
public string[] AllowedHTTPMethods = new string[] { "GET", "POST" };
#endregion
public Static() : base()
{
}
#region Methods
/// <summary>
/// ProcessRequest executed automatically by the iHttpHandler interface
/// </summary>
/// <param name="httpContext"></param>
public async Task ProcessRequest(Auth auth, UserDetail userDetail, HttpContext httpContext, CancellationTokenSource apiCancellationToken, Thread performanceThread, bool API_PERFORMANCE_ENABLED, Trace trace)
{
// Were we already canceled?
apiCancellationToken.Token.ThrowIfCancellationRequested();
try
{
Log.Instance.Info("Starting Static Processing");
httpGET = GetHttpGET(httpContext);
httpPOST = await GetHttpPOST(httpContext);
// Extract the request parameters from the URL
await ParseRequest(httpContext, apiCancellationToken);
// Check for the maintenance flag
if (Convert.ToBoolean(ApiServicesHelper.ApiConfiguration.MAINTENANCE))
{
await ParseError(httpContext, HttpStatusCode.ServiceUnavailable, apiCancellationToken,"System maintenance");
}
Static_Output result = null;
// Call the public method
if (API_PERFORMANCE_ENABLED)
{
performanceThread.Start();
}
result = GetResult(ref httpContext, userDetail, trace, auth);
trace.TrcCacheUsed = result.responseUsedCache;
if (result == null)
{
await ParseError(httpContext, HttpStatusCode.InternalServerError, apiCancellationToken, "Internal Error");
}
else if (!Utility.IsValidStatusCode((int)result.statusCode))
{
await ParseError(httpContext, HttpStatusCode.InternalServerError, apiCancellationToken, "Internal Error");
}
else if (result.statusCode == HttpStatusCode.OK)
{
httpContext.Response.ContentType = result.mimeType;
httpContext.Response.Headers["expires"]= DateTime.Now.AddYears(1).ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
httpContext.Response.Headers.Add("Last-Modified", DateTime.Now.ToString("dd/M/yyyy", CultureInfo.InvariantCulture));
httpContext.Response.Headers["Cache-Control"] = "31536000"; //one year
if (!string.IsNullOrEmpty(result.fileName))
{
httpContext.Response.Headers.Add("Content-Disposition", new ContentDisposition { Inline = true, FileName = result.fileName }.ToString());
}
if (result.response?.GetType() == typeof(byte[]))
{
// Use MemoryStream to store the byte array
using var memoryStream = new MemoryStream(result.response);
await returnResponseAsync(httpContext, result.fileName, apiCancellationToken, result.statusCode, memoryStream);
}
else
{
await returnResponseAsync(httpContext, result.response, apiCancellationToken, HttpStatusCode.OK);
}
}
else
{
await ParseError(httpContext, result.statusCode, result.response);
}
}
catch (OperationCanceledException e)
{
//don't need to do anything here as operation has been cancelled
}
catch (Exception e)
{
Log.Instance.Fatal(Utility.JsonSerialize_IgnoreLoopingReference(trace));
Log.Instance.Fatal(e);
Log.Instance.Fatal(e.StackTrace);
await returnResponseAsync(httpContext, "", apiCancellationToken, HttpStatusCode.InternalServerError);
}
}
/// <summary>
/// Parse the API error returning a HTTP status
/// </summary>
/// <param name="context"></param>
/// <param name="statusCode"></param>
/// <param name="statusDescription"></param>
private async Task ParseError(HttpContext context, HttpStatusCode statusCode,CancellationTokenSource sourceToken, string statusDescription = "")
{
Log.Instance.Info("IP: " + ApiServicesHelper.WebUtility.GetIP() + ", Status Code: " + statusCode.ToString() + ", Status Description: " + statusDescription);
if (!string.IsNullOrEmpty(statusDescription))
await returnResponseAsync(context, statusDescription, sourceToken, statusCode);
}
/// <summary>
/// Parse and validate the request
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private async Task ParseRequest(HttpContext context, CancellationTokenSource sourceToken)
{
try
{
/*
URL : http://localhost:8080/mysite/page.aspx?p1=1&p2=2
Value of HttpContext.Current.Request.Url.Host
localhost
Value of HttpContext.Current.Request.Url.Authority
localhost:8080
Value of HttpContext.Current.Request.Url.AbsolutePath
/mysite/page.aspx
Value of HttpContext.Current.Request.ApplicationPath
/
Value of HttpContext.Current.Request.Url.AbsoluteUri
http://localhost:8080/mysite/page.aspx?p1=1&p2=2
Value of HttpContext.Current.Request.RawUrl
/mysite/page.aspx?p1=1&p2=2
Value of HttpContext.Current.Request.Url.PathAndQuery
/mysite/page.aspx?p1=1&p2=2
*/
// Read the URL parameters and split the URL Absolute Path
Log.Instance.Info("URL Absolute Path: " + context.Request.Path);
RequestParams = Regex.Split(context.Request.Path, "api.static/", RegexOptions.IgnoreCase).ToList();
// Validate the Application path
if (RequestParams.Count() != 2)
{
await ParseError(context, HttpStatusCode.BadRequest, sourceToken, "Invalid Static handler");
}
// Get the Static parameters
RequestParams = RequestParams[1].Split('/').ToList();
Log.Instance.Info("Request params: " + Utility.JsonSerialize_IgnoreLoopingReference(RequestParams));
// Validate the request
if (RequestParams.Count() == 0)
{
await ParseError(context, HttpStatusCode.BadRequest, sourceToken, "Invalid Static parameters");
}
// Verify the method exists
if (!ValidateMethod(RequestParams))
{
await ParseError(context, HttpStatusCode.BadRequest, sourceToken, "Static method not found");
}
}
catch (OperationCanceledException e)
{
//don't need to do anything here as operation has been cancelled
//exit this try catch and go to next one
throw new OperationCanceledException();
}
catch (Exception e)
{
Log.Instance.Error("Request params: " + Utility.JsonSerialize_IgnoreLoopingReference(RequestParams));
Log.Instance.Error(e);
await ParseError(context, HttpStatusCode.BadRequest, sourceToken, "Bad Request");
}
}
/// <summary>
/// Validate the requested method
/// </summary>
/// <param name="requestParams"></param>
/// <returns></returns>
private static bool ValidateMethod(List<string> requestParams)
{
MethodInfo methodInfo = MapMethod(requestParams);
if (methodInfo == null)
return false;
else
return true;
}
/// <summary>
/// Map the request against the method
/// </summary>
/// <param name="requestParams"></param>
/// <returns></returns>
private static MethodInfo MapMethod(List<string> requestParams)
{
// Get Namespace(s).Class.Method
string[] mapping = requestParams[0].Split('.');
// At least 1 Namespace, 1 Class and 1 Method (3 in total) must be present
if (mapping.Length < 3)
return null;
// Get method name
string methodName = mapping[mapping.Length - 1];
// Get the method path
Array.Resize(ref mapping, mapping.Length - 1);
string methodPath = string.Join(".", mapping);
// Never allow to call Public Methods in the API Namespace
if (mapping[0].ToUpperInvariant() == "API")
return null;
// Search in the entire Assemplies till finding the right one
return CheckAPICallsAllowed(methodName, methodPath, typeof(Static_API));
}
/// <summary>
/// Invoke and return the results from the mapped method
/// </summary>
/// <returns></returns>
private dynamic GetResult(ref HttpContext context, UserDetail userDetail, Trace trace,Auth auth, Cookie sessionCookie = null)
{
// Set the API object
Static_API apiRequest = new Static_API();
apiRequest.method = RequestParams[0];
apiRequest.parameters = RequestParams;
apiRequest.ipAddress = ApiServicesHelper.WebUtility.GetIP();
apiRequest.userAgent = ApiServicesHelper.WebUtility.GetUserAgent();
//namevaluecollection not the same in .net6
apiRequest.httpGET = httpGET;
apiRequest.httpPOST = httpPOST;
apiRequest.requestType = context.Request.Method;
apiRequest.requestHeaders = context.Request.Headers;
apiRequest.correlationID = APIMiddleware.correlationID.Value;
//gather trace information
GatherTraceInformation(apiRequest, trace);
Log.Instance.Info("API Request: " + MaskParameters(Utility.JsonSerialize_IgnoreLoopingReference(userDetail)));
// Verify the method exists
MethodInfo methodInfo = MapMethod(RequestParams);
//Invoke the API Method
return methodInfo.Invoke(null, new object[] { apiRequest });
}
/// <summary>
/// Handle reusable IHttpHandler instances
/// </summary>
public bool IsReusable
{
// Set to false to ensure thread safe operations
get { return true; }
}
#endregion
}
/// <summary>
/// Define the Output structure required by the exposed API
/// </summary>
public class Static_Output
{
#region Properties
/// <summary>
/// Static response
/// </summary>
public dynamic response { get; set; }
/// <summary>
/// Static mime type
/// </summary>
public string mimeType { get; set; }
/// <summary>
/// Static status code
/// </summary>
public HttpStatusCode statusCode { get; set; }
/// <summary>
/// Static filename (optional)
/// </summary>
public string fileName { get; set; }
/// <summary>
/// request used cache
/// </summary>
public bool? responseUsedCache { get; set; }
#endregion
}
/// <summary>
/// Define the API Class to pass to the exposed API
/// </summary>
public class Static_API : IRequest
{
#region Properties
/// <summary>
/// API method
/// </summary>
public string method { get; set; }
/// <summary>
/// API parameters
/// </summary>
public dynamic parameters { get; set; }
/// <summary>
/// Client IP address
/// </summary>
public string ipAddress { get; set; }
/// <summary>
/// Client user agent
/// </summary>
public string userAgent { get; set; }
/// <summary>
/// GET request
/// </summary>
public NameValueCollection httpGET { get; set; }
/// <summary>
/// POST request
/// </summary>
public string httpPOST { get; set; }
// public dynamic userPrincipal { get { return null; } set { } }
public UserDetail userDetail { get { return null; } set { } }
public Cookie sessionCookie { get { return null; } set { } }
/// <summary>
/// Request Type
/// </summary>
public string requestType { get; set; }
#endregion
/// <summary>
/// Request Headers
/// </summary>
public IHeaderDictionary requestHeaders { get; set; }
/// <summary>
/// Request Scheme
/// </summary>
public string scheme { get; set; }
/// <summary>
/// Request correlatationID
/// </summary>
public string correlationID { get; set; }
}
}