-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtility.cs
1372 lines (1233 loc) · 57.7 KB
/
Utility.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
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region Related components
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using net.vieapps.Components.WebSockets;
using net.vieapps.Components.Security;
#endregion
#if !SIGN
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("VIEApps.Components.XUnitTests")]
#endif
namespace net.vieapps.Components.Utility
{
/// <summary>
/// Static servicing methods for working with ASP.NET Core
/// </summary>
public static partial class AspNetCoreUtilityService
{
/// <summary>
/// Gets or Sets the name of server to write into headers
/// </summary>
public static string ServerName { get; set; } = "VIEApps NGX";
/// <summary>
/// Gets the size for buffering when read/write a stream (default is 64K)
/// </summary>
public static int BufferSize => 1024 * 64;
#region Extensions for working with environments
/// <summary>
/// Gets the approriate HTTP Status Code of the exception
/// </summary>
/// <param name="exception"></param>
/// <returns></returns>
public static int GetHttpStatusCode(this Exception exception)
{
if (exception is FileNotFoundException || exception is ServiceNotFoundException || exception is InformationNotFoundException)
return (int)HttpStatusCode.NotFound;
if (exception is AccessDeniedException)
return (int)HttpStatusCode.Forbidden;
if (exception is UnauthorizedException)
return (int)HttpStatusCode.Unauthorized;
if (exception is MethodNotAllowedException)
return (int)HttpStatusCode.MethodNotAllowed;
if (exception is InvalidRequestException)
return (int)HttpStatusCode.BadRequest;
if (exception is NotImplementedException)
return (int)HttpStatusCode.NotImplemented;
if (exception is ConnectionTimeoutException)
return (int)HttpStatusCode.RequestTimeout;
if (exception is OperationCanceledException)
return (int)HttpStatusCode.BadGateway;
return exception.GetTypeName(true).IsEndsWith("NotFound")
? (int)HttpStatusCode.NotFound
: (int)HttpStatusCode.InternalServerError;
}
/// <summary>
/// Gets the name of server
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetServerName(this HttpContext context)
=> string.IsNullOrWhiteSpace(AspNetCoreUtilityService.ServerName) ? "VIEApps NGX" : AspNetCoreUtilityService.ServerName;
/// <summary>
/// Gets the HTML body of a status code
/// </summary>
/// <param name="context"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public static string GetHttpStatusCodeBody(this HttpContext context, int statusCode, string message = null, string type = null, string correlationID = null, string stack = null, bool showStack = true)
{
statusCode = statusCode < 1 ? (int)HttpStatusCode.InternalServerError : statusCode;
var html = "<!DOCTYPE html>\r\n" +
$"<html xmlns=\"http://www.w3.org/1999/xhtml\">\r\n" +
$"<head>\r\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\r\n<title>Error {statusCode}</title>\r\n</head>\r\n<body>\r\n" +
$"<h1>HTTP {statusCode}{(string.IsNullOrWhiteSpace(message) ? "" : $" - {message.Replace("<", "<").Replace(">", ">")}")}</h1>\r\n";
if (!string.IsNullOrWhiteSpace(type))
html += $"<hr/>\r\n<div>Type: {type}</div>\r\n";
if (!string.IsNullOrWhiteSpace(stack) && showStack)
html += $"<div>Stack:</div>\r\n<blockquote>{stack.Replace("<", "<").Replace(">", ">").Replace("\n", "<br/>").Replace("\r", "").Replace("\t", "")}</blockquote>\r\n";
html += $"<hr/>\r\n"
+ $"<div>{(!string.IsNullOrWhiteSpace(correlationID) ? $"Correlation ID: {correlationID} - " : "")}"
+ $"Powered by {context.GetServerName()} v{Assembly.GetExecutingAssembly().GetVersion(false)}</div>\r\n"
+ "</body>\r\n</html>";
return html;
}
static FileExtensionContentTypeProvider MimeTypeProvider { get; } = new FileExtensionContentTypeProvider();
/// <summary>
/// Gets the MIME type of a file
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public static string GetMimeType(this string filename)
=> AspNetCoreUtilityService.MimeTypeProvider.TryGetContentType(filename, out var mimeType) && !string.IsNullOrWhiteSpace(mimeType) ? mimeType : "application/octet-stream; charset=utf-8";
/// <summary>
/// Gets the MIME type of a file
/// </summary>
/// <param name="fileInfo"></param>
/// <returns></returns>
public static string GetMimeType(this FileInfo fileInfo)
=> fileInfo?.Name?.GetMimeType() ?? "application/octet-stream; charset=utf-8";
/// <summary>
/// Parses the query of an uri
/// </summary>
/// <param name="uri"></param>
/// /// <param name="onCompleted">Action to run on parsing completed</param>
/// <returns>The collection of key and value pair</returns>
public static Dictionary<string, string> ParseQuery(this Uri uri, Action<Dictionary<string, string>> onCompleted = null)
=> QueryHelpers.ParseQuery(uri.Query).ToDictionary(onCompleted);
/// <summary>
/// Parses the query of the request in this context
/// </summary>
/// <param name="context"></param>
/// /// <param name="onCompleted">Action to run on parsing completed</param>
/// <returns>The collection of key and value pair</returns>
public static Dictionary<string, string> ParseQuery(this HttpContext context, Action<Dictionary<string, string>> onCompleted = null)
=> context.GetRequestUri().ParseQuery(onCompleted);
/// <summary>
/// Tries to get the value of a header parameter
/// </summary>
/// <param name="context"></param>
/// <param name="name">The string that presents name of parameter want to get</param>
/// <returns></returns>
public static bool TryGetHeaderParameter(this HttpContext context, string name, out string value)
{
value = null;
return !string.IsNullOrWhiteSpace(name) && context.Request.Headers.ToDictionary().TryGetValue(name, out value);
}
/// <summary>
/// Gets the value of a header parameter
/// </summary>
/// <param name="context"></param>
/// <param name="name">The string that presents name of parameter want to get</param>
/// <returns></returns>
public static string GetHeaderParameter(this HttpContext context, string name)
=> context.TryGetHeaderParameter(name, out var value) && !string.IsNullOrWhiteSpace(value) ? value : null;
/// <summary>
/// Tries to get the value of a query parameter
/// </summary>
/// <param name="context"></param>
/// <param name="name">The string that presents name of parameter want to get</param>
/// <returns></returns>
public static bool TryGetQueryParameter(this HttpContext context, string name, out string value)
{
value = null;
return !string.IsNullOrWhiteSpace(name) && context.Request.QueryString.ToDictionary().TryGetValue(name, out value);
}
/// <summary>
/// Gets the value of a query parameter
/// </summary>
/// <param name="context"></param>
/// <param name="name">The string that presents name of parameter want to get</param>
/// <returns></returns>
public static string GetQueryParameter(this HttpContext context, string name)
=> context.TryGetQueryParameter(name, out var value) && !string.IsNullOrWhiteSpace(value) ? value : null;
/// <summary>
/// Gets the value of a parameter (first from header, if not found then get from query string)
/// </summary>
/// <param name="context"></param>
/// <param name="name">The string that presents name of parameter want to get</param>
/// <returns></returns>
public static bool TryGetParameter(this HttpContext context, string name, out string value)
=> context.TryGetHeaderParameter(name, out value) || context.TryGetQueryParameter(name, out value);
/// <summary>
/// Gets the value of a parameter (first from header, if not found then get from query string)
/// </summary>
/// <param name="context"></param>
/// <param name="name">The string that presents name of parameter want to get</param>
/// <returns></returns>
public static string GetParameter(this HttpContext context, string name)
=> context.GetHeaderParameter(name) ?? context.GetQueryParameter(name);
/// <summary>
/// Gets the original Uniform Resource Identifier (URI) of the request that was sent by the client
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static Uri GetUri(this HttpContext context)
=> new Uri($"{context.Request.Scheme}://{context.Request.Host}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}");
/// <summary>
/// Gets the original Uniform Resource Identifier (URI) of the request that was sent by the client
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static Uri GetRequestUri(this HttpContext context)
=> context.GetUri();
/// <summary>
/// Gets the url of current uri that not include query-string
/// </summary>
/// <param name="uri"></param>
/// <param name="toLower"></param>
/// <param name="useRelativeUrl"></param>
/// <returns></returns>
public static string GetUrl(this Uri uri, bool toLower = false, bool useRelativeUrl = false)
{
var url = useRelativeUrl ? uri.PathAndQuery : uri.ToString();
url = toLower ? url.ToLower() : url;
var pos = url.IndexOf("?");
return pos > 0 ? url.Left(pos) : url;
}
/// <summary>
/// Gets the url of current request (query-string is excluded)
/// </summary>
/// <param name="context"></param>
/// <param name="toLower"></param>
/// <param name="useRelativeUrl"></param>
/// <returns></returns>
public static string GetRequestUrl(this HttpContext context, bool toLower = false, bool useRelativeUrl = false)
=> context.GetRequestUri().GetUrl(toLower, useRelativeUrl);
/// <summary>
/// Gets the host url (scheme, host and port - if not equals to default)
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public static string GetHostUrl(this Uri uri)
=> uri.Scheme + "://" + uri.Host + (uri.Port != 80 && uri.Port != 443 ? $":{uri.Port}" : "");
/// <summary>
/// Gets the host url (scheme, host and port - if not equals to default)
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetHostUrl(this HttpContext context)
=> context.GetRequestUri().GetHostUrl();
/// <summary>
/// Gets path segments of this uri
/// </summary>
/// <param name="uri"></param>
/// <param name="toLower"></param>
/// <returns></returns>
public static string[] GetRequestPathSegments(this Uri uri, bool toLower = false)
{
var path = uri.GetUrl(toLower, true);
return path.Equals("/") || path.Equals("~/")
? new[] { "" }
: path.ToArray('/', true);
}
/// <summary>
/// Gets path segments of this request
/// </summary>
/// <param name="context"></param>
/// <param name="toLower"></param>
/// <returns></returns>
public static string[] GetRequestPathSegments(this HttpContext context, bool toLower = false)
=> context.GetRequestUri().GetRequestPathSegments(toLower);
/// <summary>
/// Gets the refer Uniform Resource Identifier (URI) of the request that was sent by the client
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static Uri GetReferUri(this HttpContext context)
=> context.TryGetHeaderParameter("Referer", out var value) && !string.IsNullOrWhiteSpace(value)
? new Uri(value)
: null;
/// <summary>
/// Gets the origin Uniform Resource Identifier (URI) of the request that was sent by the client
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static Uri GetOriginUri(this HttpContext context)
=> context.TryGetHeaderParameter("Origin", out var value) && !string.IsNullOrWhiteSpace(value)
? new Uri(value)
: null;
/// <summary>
/// Gets the user-agent string of the request that was sent by the client
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetUserAgent(this HttpContext context)
=> context.GetHeaderParameter("User-Agent") ?? "";
/// <summary>
/// Gets the local endpoint
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static IPEndPoint GetLocalEndPoint(this HttpContext context)
=> new IPEndPoint(context.Connection.LocalIpAddress, context.Connection.LocalPort);
/// <summary>
/// Gets the remote endpoint
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static IPEndPoint GetRemoteEndPoint(this HttpContext context)
{
var endpoint = new IPEndPoint(context.Connection.RemoteIpAddress, context.Connection.RemotePort);
if (endpoint.Port == 0)
try
{
var uri = context.TryGetHeaderParameter("x-original-remote-endpoint", out var value)
? new Uri(value)
: context.TryGetHeaderParameter("cf-connecting-ip", out value)
? new Uri($"https://{value}:{new Uri($"https://{context.GetHeaderParameter("x-original-for")}").Port}")
: new Uri($"https://{context.GetHeaderParameter("x-original-for")}");
endpoint = new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port);
}
catch { }
return endpoint;
}
/// <summary>
/// Appends cookies into response
/// </summary>
/// <param name="context"></param>
/// <param name="cookies"></param>
public static void AppendCookies(this HttpContext context, IEnumerable<Cookie> cookies)
{
cookies?.ForEach(cookie => context.Response.Cookies.Append
(
cookie.Name,
cookie.Value,
new CookieOptions
{
Domain = cookie.Domain,
Path = cookie.Path,
Expires = cookie.Expires,
Secure = cookie.Secure,
HttpOnly = cookie.HttpOnly
}
));
}
/// <summary>
/// Gets the request content-encoding
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetContentEncoding(this HttpContext context)
{
var encoding = context.Request.Headers["Accept-Encoding"].ToString();
return encoding.IsContains("br") || encoding.IsContains("*")
? "br"
: encoding.IsContains("gzip")
? "gzip"
: encoding.IsContains("deflate")
? "deflate"
: null;
}
/// <summary>
/// Gets the request ETag
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static string GetRequestETag(this HttpContext context)
{
// IE or common browser
var requestETag = context.Request.Headers["If-Range"].First();
// FireFox
if (string.IsNullOrWhiteSpace(requestETag))
requestETag = context.Request.Headers["If-Match"].First();
// normalize
if (!string.IsNullOrWhiteSpace(requestETag))
{
while (requestETag.StartsWith("\""))
requestETag = requestETag.Right(requestETag.Length - 1);
while (requestETag.EndsWith("\""))
requestETag = requestETag.Left(requestETag.Length - 1);
}
// return the request ETag for resume downloading
return requestETag;
}
/// <summary>
/// Generates ETag from this uri
/// </summary>
/// <param name="uri"></param>
/// <param name="prefix"></param>
/// <param name="queryIncluded"></param>
/// <returns></returns>
public static string GenerateETag(this Uri uri, string prefix = null, bool queryIncluded = false)
=> $"{prefix ?? "v"}#{(queryIncluded ? $"{uri}".ToLower() : uri.GetUrl(true, false)).GenerateUUID()}";
/// <summary>
/// Generates ETag from the uri of this context
/// </summary>
/// <param name="context"></param>
/// <param name="prefix"></param>
/// <param name="queryIncluded"></param>
/// <returns></returns>
public static string GenerateETag(this HttpContext context, string prefix = null, bool queryIncluded = false)
=> context.GetRequestUri().GenerateETag(prefix, queryIncluded);
#endregion
#region Read data from request
/// <summary>
/// Reads data from request body asynchronously
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static async Task<byte[]> ReadAsync(this HttpContext context, CancellationToken cancellationToken = default)
{
var buffer = new byte[AspNetCoreUtilityService.BufferSize];
var data = Array.Empty<byte>();
int read;
do
{
read = await context.Request.Body.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
if (read > 0)
data = data.Concat(buffer.Take(0, read));
}
while (read > 0);
return data;
}
/// <summary>
/// Reads data as text from request body asynchronously
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static Task<string> ReadTextAsync(this HttpContext context, CancellationToken cancellationToken = default)
=> context.Request.Body.ReadAllAsync(cancellationToken);
#endregion
#region Response helpers: set headers, flush, redirect, ...
/// <summary>
/// Sets the approriate headers of response
/// </summary>
/// <param name="context"></param>
/// <param name="statusCode">The HTTP status code</param>
/// <param name="headers">The HTTP headers</param>
public static void SetResponseHeaders(this HttpContext context, int statusCode, Dictionary<string, string> headers = null)
{
// prepare
headers = new Dictionary<string, string>(headers ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase)
{
["Server"] = context.GetServerName(),
["X-Powered-By"] = $"{context.GetServerName()} v{Assembly.GetExecutingAssembly().GetVersion(false)}"
};
if (context.Items.TryGetValue("PipelineStopwatch", out var swatch) && swatch is Stopwatch stopwatch)
{
stopwatch.Stop();
headers["X-Execution-Times"] = stopwatch.GetElapsedTimes();
}
headers.TryGetValue("Content-Type", out var contentType);
if (!string.IsNullOrWhiteSpace(contentType) && !contentType.IsEndsWith("; charset=utf-8"))
headers["Content-Type"] = $"{contentType}; charset=utf-8";
// update into context to use at status page middleware
context.SetItem("StatusCode", statusCode);
context.SetItem("Body", "");
context.SetItem("Headers", headers);
if (headers.TryGetValue("Cache-Control", out var cacheControl))
context.SetItem("CacheControl", cacheControl);
// update headers
headers.ForEach(kvp => context.Response.Headers[kvp.Key] = kvp.Value);
context.Response.StatusCode = statusCode;
}
/// <summary>
/// Sets the approriate headers of response
/// </summary>
/// <param name="context"></param>
/// <param name="statusCode">The HTTP status code</param>
/// <param name="contentType">The MIME content type</param>
/// <param name="eTag">The entity tag</param>
/// <param name="lastModified">The number that presents Unix timestamp</param>
/// <param name="correlationID">The correlation idenntity</param>
/// <param name="headers">The additional headers</param>
public static void SetResponseHeaders(this HttpContext context, int statusCode, string contentType, string eTag, long lastModified, string cacheControl, TimeSpan expires, string correlationID = null, Dictionary<string, string> headers = null)
{
// prepare
headers = new Dictionary<string, string>(headers ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(contentType))
headers["Content-Type"] = $"{contentType}{(contentType.IsEndsWith("; charset=utf-8") ? "" : "; charset=utf-8")}";
if (!string.IsNullOrWhiteSpace(eTag))
headers["ETag"] = eTag;
if (lastModified > 0)
headers["Last-Modified"] = lastModified.FromUnixTimestamp().ToHttpString();
if (!string.IsNullOrWhiteSpace(cacheControl))
{
headers["Cache-Control"] = cacheControl;
if (expires != default && expires.Ticks > 0)
headers["Expires"] = DateTime.Now.Add(expires).ToHttpString();
}
if (!string.IsNullOrWhiteSpace(correlationID))
headers["X-Correlation-ID"] = correlationID;
// update
context.SetResponseHeaders(statusCode, headers);
}
/// <summary>
/// Set response headers with special status code for using with StatusCodeHandler (UseStatusCodePages middleware)
/// </summary>
/// <param name="context"></param>
/// <param name="statusCode"></param>
/// <param name="eTag"></param>
/// <param name="lastModified"></param>
/// <param name="cacheControl"></param>
/// <param name="correlationID"></param>
/// <param name="headers"></param>
public static void SetResponseHeaders(this HttpContext context, int statusCode, string eTag, long lastModified, string cacheControl, string correlationID, Dictionary<string, string> headers = null)
{
// prepare headers
headers = new Dictionary<string, string>(headers ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(eTag))
headers["ETag"] = eTag;
if (lastModified > 0)
headers["Last-Modified"] = lastModified.FromUnixTimestamp().ToHttpString();
if (!string.IsNullOrWhiteSpace(cacheControl))
headers["Cache-Control"] = cacheControl;
if (!string.IsNullOrWhiteSpace(correlationID))
headers["X-Correlation-ID"] = correlationID;
// update
context.SetResponseHeaders(statusCode, headers);
}
/// <summary>
/// Asynchronously sends all currently buffered output to the client
/// </summary>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
public static Task FlushAsync(this HttpContext context, CancellationToken cancellationToken = default)
=> context.Response.Body.FlushAsync(cancellationToken);
/// <summary>
/// Redirects the response by send the redirect status code (301 or 302) to client
/// </summary>
/// <param name="context"></param>
/// <param name="location">The location to redirect to - must be encoded</param>
/// <param name="redirectPermanently">true to use 301 (Moved Permanently) instead of 302 (Redirect Temporary)</param>
public static void Redirect(this HttpContext context, string location, bool redirectPermanently = false)
{
if (!string.IsNullOrWhiteSpace(location))
context.SetResponseHeaders(redirectPermanently ? (int)HttpStatusCode.MovedPermanently : (int)HttpStatusCode.Redirect, new Dictionary<string, string> { ["Location"] = location });
}
/// <summary>
/// Redirects the response by send the redirect status code (301 or 302) to client
/// </summary>
/// <param name="context"></param>
/// <param name="uri">The location to redirect to</param>
/// <param name="redirectPermanently">true to use 301 (Moved Permanently) instead of 302 (Redirect Temporary)</param>
public static void Redirect(this HttpContext context, Uri uri, bool redirectPermanently = false)
{
if (uri == null)
return;
var location = $"{uri.Scheme}://{uri.Host}{(uri.Port != 80 && uri.Port != 443 ? $":{uri.Port}" : "")}/";
var pathSegments = uri.GetRequestPathSegments();
if (pathSegments != null && pathSegments.Length > 0)
location += pathSegments.ToString("/", segment => segment.UrlDecode().UrlEncode());
var query = uri.ParseQuery();
if (query != null && query.Count > 0)
location += "?" + query.ToString("&", kvp => $"{kvp.Key.UrlEncode()}={kvp.Value.UrlDecode().UrlEncode()}");
if (!string.IsNullOrWhiteSpace(uri.Fragment))
location += uri.Fragment;
context.Redirect(location, redirectPermanently);
}
#endregion
#region Write a stream to the response body
/// <summary>
/// Writes the stream to the output response body
/// </summary>
/// <param name="context"></param>
/// <param name="stream">The stream to write</param>
/// <param name="headers">The headers</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static async Task WriteAsync(this HttpContext context, Stream stream, Dictionary<string, string> headers, IEnumerable<Cookie> cookies, CancellationToken cancellationToken)
{
// prepare headers
headers = new Dictionary<string, string>(headers ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase);
// check ETag for supporting resumeable downloaders
headers.TryGetValue("ETag", out var eTag);
if (!string.IsNullOrWhiteSpace(eTag))
{
var requestETag = context.GetRequestETag();
if (!string.IsNullOrWhiteSpace(requestETag) && !eTag.Equals(requestETag))
{
context.SetResponseHeaders((int)HttpStatusCode.PreconditionFailed, null, 0, "private", null);
await context.FlushAsync(cancellationToken).ConfigureAwait(false);
return;
}
}
// prepare position for flushing as partial blocks
var asPartialContent = false;
var totalBytes = stream.Length;
long startBytes = 0, endBytes = totalBytes - 1;
var requestedRange = context.Request.Headers["Range"].First();
if (!string.IsNullOrWhiteSpace(requestedRange))
{
asPartialContent = true;
var range = requestedRange.ToList("=").Last().ToList("-");
startBytes = range[0].As<long>();
if (startBytes >= totalBytes)
{
context.SetResponseHeaders((int)HttpStatusCode.PreconditionFailed, null, 0, "private", null);
return;
}
if (startBytes < 0)
startBytes = 0;
if (range.Count > 1)
try
{
endBytes = range[1].As<long>();
}
catch { }
if (endBytes > totalBytes - 1)
endBytes = totalBytes - 1;
}
if (!string.IsNullOrWhiteSpace(eTag))
headers["Accept-Ranges"] = "bytes";
if (asPartialContent)
{
headers["Content-Length"] = $"{endBytes - startBytes + 1}";
if (startBytes > -1)
headers["Content-Range"] = $"bytes {startBytes}-{endBytes}/{totalBytes}";
}
// update headers & cookies
context.SetResponseHeaders(asPartialContent ? (int)HttpStatusCode.PartialContent : (int)HttpStatusCode.OK, headers);
context.AppendCookies(cookies);
// read and flush stream data to response stream
if (asPartialContent && startBytes > 0)
stream.Seek(startBytes, SeekOrigin.Begin);
var size = AspNetCoreUtilityService.BufferSize;
if (size > (endBytes - startBytes))
size = (int)(endBytes - startBytes) + 1;
var buffer = new byte[size];
var total = (int)Math.Ceiling((endBytes - startBytes + 0.0) / size);
var count = 0;
while (count < total)
{
var read = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
#if NETSTANDARD2_0
await context.Response.Body.WriteAsync(buffer, 0, read, cancellationToken).ConfigureAwait(false);
#else
await context.Response.Body.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false);
#endif
await context.Response.Body.FlushAsync(cancellationToken).ConfigureAwait(false);
count++;
}
}
/// <summary>
/// Writes the stream to the output response body
/// </summary>
/// <param name="context"></param>
/// <param name="stream">The stream to write</param>
/// <param name="headers">The headers</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, Stream stream, Dictionary<string, string> headers, CancellationToken cancellationToken = default)
=> context.WriteAsync(stream, headers, null, cancellationToken);
/// <summary>
/// Writes the stream to the output response body
/// </summary>
/// <param name="context"></param>
/// <param name="stream">The stream to write</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, Stream stream, CancellationToken cancellationToken = default)
=> context.WriteAsync(stream, null, null, cancellationToken);
/// <summary>
/// Writes the stream to the output response body
/// </summary>
/// <param name="context"></param>
/// <param name="stream">The stream to write</param>
/// <param name="contentType">The MIME type</param>
/// <param name="contentDisposition">The string that presents name of attachment file, let it empty/null for writting showing/displaying (not for downloading attachment file)</param>
/// <param name="eTag">The entity tag</param>
/// <param name="lastModified">The Unix timestamp that presents last-modified time</param>
/// <param name="cacheControl">The string that presents cache control ('public', 'private', 'no-store')</param>
/// <param name="expires">The timespan that presents expires time of cache</param>
/// <param name="headers">The additional headers</param>
/// <param name="correlationID">The correlation identity</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, Stream stream, string contentType, string contentDisposition = null, string eTag = null, long lastModified = 0, string cacheControl = null, TimeSpan expires = default, Dictionary<string, string> headers = null, string correlationID = null, CancellationToken cancellationToken = default)
{
// prepare headers
headers = new Dictionary<string, string>(headers ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(contentType))
headers["Content-Type"] = contentType;
if (!string.IsNullOrWhiteSpace(contentDisposition))
headers["Content-Disposition"] = $"Attachment; Filename=\"{contentDisposition.UrlEncode()}\"";
if (!string.IsNullOrWhiteSpace(eTag))
headers["ETag"] = eTag;
if (lastModified > 0)
headers["Last-Modified"] = lastModified.FromUnixTimestamp().ToHttpString();
if (!string.IsNullOrWhiteSpace(cacheControl))
{
headers["Cache-Control"] = cacheControl;
if (expires != default && expires.Ticks > 0)
headers["Expires"] = DateTime.Now.Add(expires).ToHttpString();
}
if (!string.IsNullOrWhiteSpace(correlationID))
headers["X-Correlation-ID"] = correlationID;
// write
return context.WriteAsync(stream, headers, cancellationToken);
}
/// <summary>
/// Writes the stream to the output response body
/// </summary>
/// <param name="context"></param>
/// <param name="stream">The stream to write</param>
/// <param name="contentType">The MIME type</param>
/// <param name="contentDisposition">The string that presents name of attachment file, let it empty/null for writting showing/displaying (not for downloading attachment file)</param>
/// <param name="eTag">The entity tag</param>
/// <param name="lastModified">The Unix timestamp that presents last-modified time</param>
/// <param name="cacheControl">The string that presents cache control ('public', 'private', 'no-store')</param>
/// <param name="expires">The timespan that presents expires time of cache</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, Stream stream, string contentType, string contentDisposition, string eTag, long lastModified, string cacheControl, TimeSpan expires, CancellationToken cancellationToken = default)
=> context.WriteAsync(stream, contentType, contentDisposition, eTag, lastModified, cacheControl, expires, null, null, cancellationToken);
#endregion
#region Write a file to the response body
/// <summary>
/// Writes the content of a file (binary) to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="fileInfo">The information of the file to write to output stream</param>
/// <param name="contentType">The MIME type</param>
/// <param name="contentDisposition">The string that presents name of attachment file, let it empty/null for writting showing/displaying (not for downloading attachment file)</param>
/// <param name="eTag">The entity tag</param>
/// <param name="lastModified">The Unix timestamp that presents last-modified time</param>
/// <param name="cacheControl">The string that presents cache control ('public', 'private', 'no-store')</param>
/// <param name="expires">The timespan that presents expires time of cache</param>
/// <param name="headers">The additional headers</param>
/// <param name="correlationID">The correlation identity</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static async Task WriteAsync(this HttpContext context, FileInfo fileInfo, string contentType = null, string contentDisposition = null, string eTag = null, long lastModified = 0, string cacheControl = null, TimeSpan expires = default, Dictionary<string, string> headers = null, string correlationID = null, CancellationToken cancellationToken = default)
{
if (fileInfo == null || !fileInfo.Exists)
throw new FileNotFoundException($"Not found{(fileInfo != null ? $" [{fileInfo.Name}]" : "")}");
using (var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, AspNetCoreUtilityService.BufferSize, true))
await context.WriteAsync
(
stream,
contentType ?? fileInfo.GetMimeType(),
contentDisposition,
eTag,
string.IsNullOrWhiteSpace(eTag) ? 0 : lastModified > 0 ? lastModified : fileInfo.LastWriteTime.ToUnixTimestamp(),
string.IsNullOrWhiteSpace(eTag) ? null : cacheControl ?? "public",
string.IsNullOrWhiteSpace(eTag) ? TimeSpan.Zero : expires != TimeSpan.Zero && expires.Ticks > 0 ? expires : TimeSpan.FromDays(366),
headers,
correlationID,
cancellationToken
).ConfigureAwait(false);
}
/// <summary>
/// Writes the content of a file (binary) to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="fileInfo">The information of the file to write to output stream</param>
/// <param name="contentType">The MIME type</param>
/// <param name="contentDisposition">The string that presents name of attachment file, let it empty/null for writting showing/displaying (not for downloading attachment file)</param>
/// <param name="eTag">The entity tag</param>
/// <param name="correlationID">The correlation identity</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, FileInfo fileInfo, string contentType, string contentDisposition = null, string eTag = null, string correlationID = null, CancellationToken cancellationToken = default)
=> context.WriteAsync(fileInfo, contentType, contentDisposition, eTag, 0, null, TimeSpan.Zero, null, correlationID, cancellationToken);
/// <summary>
/// Writes the content of a file (binary) to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="fileInfo">The information of the file</param>
/// <param name="contentDisposition">The string that presents name of attachment file, let it empty/null for writting showing/displaying (not for downloading attachment file)</param>
/// <param name="eTag">The entity tag</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, FileInfo fileInfo, string contentDisposition, string eTag = null, CancellationToken cancellationToken = default)
=> context.WriteAsync(fileInfo, null, contentDisposition, eTag, null, cancellationToken);
/// <summary>
/// Writes the content of a file (binary) to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="fileInfo">The information of the file</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, FileInfo fileInfo, CancellationToken cancellationToken = default)
=> context.WriteAsync(fileInfo, null, null, cancellationToken);
#endregion
#region Write binary data to the response body
/// <summary>
/// Writes binary data to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <param name="headers"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task WriteAsync(this HttpContext context, byte[] buffer, int offset, int count, Dictionary<string, string> headers, CancellationToken cancellationToken = default)
{
using (var stream = (buffer == null ? Array.Empty<byte>() : buffer.Take(offset > -1 ? offset : 0, count > 0 ? count : buffer.Length)).ToMemoryStream())
await context.WriteAsync(stream, headers, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Writes binary data to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="buffer"></param>
/// <param name="headers"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, byte[] buffer, Dictionary<string, string> headers, CancellationToken cancellationToken = default)
=> context.WriteAsync(buffer, 0, 0, headers, cancellationToken);
/// <summary>
/// Writes binary data to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, byte[] buffer, int offset = 0, int count = 0, CancellationToken cancellationToken = default)
=> context.WriteAsync(buffer, offset, count, null, cancellationToken);
/// <summary>
/// Writes binary data to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="buffer"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, byte[] buffer, CancellationToken cancellationToken)
=> context.WriteAsync(buffer, 0, 0, cancellationToken);
/// <summary>
/// Writes binary data to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="buffer"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, ArraySegment<byte> buffer, CancellationToken cancellationToken = default)
=> context.WriteAsync(buffer.ToBytes(), cancellationToken);
/// <summary>
/// Writes binary data to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="buffer">The data to write</param>
/// <param name="contentType">The MIME type</param>
/// <param name="contentDisposition">The string that presents name of attachment file, let it empty/null for writting showing/displaying (not for downloading attachment file)</param>
/// <param name="eTag">The entity tag</param>
/// <param name="lastModified">The Unix timestamp that presents last-modified time</param>
/// <param name="cacheControl">The string that presents cache control ('public', 'private', 'no-store')</param>
/// <param name="expires">The timespan that presents expires time of cache</param>
/// <param name="headers">The additional headers</param>
/// <param name="correlationID">The correlation identity</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static async Task WriteAsync(this HttpContext context, byte[] buffer, string contentType, string contentDisposition = null, string eTag = null, long lastModified = 0, string cacheControl = null, TimeSpan expires = default, Dictionary<string, string> headers = null, string correlationID = null, CancellationToken cancellationToken = default)
{
using (var stream = (buffer ?? Array.Empty<byte>()).ToMemoryStream())
await context.WriteAsync(stream, contentType, contentDisposition, eTag, lastModified, cacheControl, expires, headers, correlationID, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Writes binary data to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="buffer">The data to write</param>
/// <param name="contentType">The MIME type</param>
/// <param name="contentDisposition">The string that presents name of attachment file, let it empty/null for writting showing/displaying (not for downloading attachment file)</param>
/// <param name="eTag">The entity tag</param>
/// <param name="lastModified">The Unix timestamp that presents last-modified time</param>
/// <param name="cacheControl">The string that presents cache control ('public', 'private', 'no-store')</param>
/// <param name="expires">The timespan that presents expires time of cache</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, byte[] buffer, string contentType, string contentDisposition, string eTag, long lastModified, string cacheControl, TimeSpan expires, CancellationToken cancellationToken = default)
=> context.WriteAsync(buffer, contentType, contentDisposition, eTag, lastModified, cacheControl, expires, null, null, cancellationToken);
#endregion
#region Write text data to the response body
/// <summary>
/// Writes the given text to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="text"></param>
/// <param name="headers"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, string text, Dictionary<string, string> headers, CancellationToken cancellationToken = default)
=> context.WriteAsync
(
text?.ToBytes() ?? Array.Empty<byte>(),
new Dictionary<string, string>(headers ?? new Dictionary<string, string>(), StringComparer.OrdinalIgnoreCase)
{
["Content-Type"] = headers != null && headers.TryGetValue("Content-Type", out var contentType) && !string.IsNullOrWhiteSpace(contentType) ? contentType : "text/html"
},
cancellationToken
);
/// <summary>
/// Writes the given text to the response body
/// </summary>
/// <param name="context"></param>
/// <param name="text"></param>
/// <param name="encoding"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task WriteAsync(this HttpContext context, string text, Encoding encoding = null, CancellationToken cancellationToken = default)
=> context.WriteAsync(text.ToBytes(encoding), cancellationToken);
/// <summary>
/// Writes the given text to the response body