-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathHttpHelper.cs
More file actions
1372 lines (1312 loc) · 40.5 KB
/
HttpHelper.cs
File metadata and controls
1372 lines (1312 loc) · 40.5 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
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
using GeneXus.Application;
using GeneXus.Configuration;
using GeneXus.Utils;
#if NETCORE
using GxClasses.Helpers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Primitives;
using Microsoft.AspNetCore.Mvc.Formatters;
using System.Reflection;
#else
using System.ServiceModel.Web;
using System.ServiceModel;
using System.ServiceModel.Channels;
#endif
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Runtime.Serialization;
using GeneXus.Mime;
using System.Text.RegularExpressions;
using Microsoft.Net.Http.Headers;
using System.Net.Http;
using System.Globalization;
using System.Linq;
using GeneXus.Http.Client;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Threading;
namespace GeneXus.Http
{
public enum GAMSecurityLevel
{
SecurityHigh = 2,
SecurityLow = 1,
SecurityNone = 0,
SecurityObject = 3
}
public class HttpHeader
{
public static string AUTHENTICATE_HEADER = "WWW-Authenticate";
public static string WARNING_HEADER = "Warning";
public static string CONTENT_DISPOSITION = "Content-Disposition";
public static string CACHE_CONTROL = "Cache-Control";
public static string LAST_MODIFIED = "Last-Modified";
public static string EXPIRES = "Expires";
public static string XGXFILENAME = "x-gx-filename";
public static string GX_OBJECT_ID = "GeneXus-Object-Id";
internal static string ACCEPT = "Accept";
internal static string TRANSFER_ENCODING = "Transfer-Encoding";
internal static string X_CSRF_TOKEN_HEADER = "X-XSRF-TOKEN";
internal static string X_CSRF_TOKEN_COOKIE = "XSRF-TOKEN";
internal static string AUTHORIZATION = "Authorization";
internal static string CONTENT_TYPE = "Content-Type";
internal static string USER_AGENT = "User-Agent";
}
internal class HttpHeaderValue
{
internal static string ACCEPT_SERVER_SENT_EVENT = "text/event-stream";
internal static string TRANSFER_ENCODING_CHUNKED = "chunked";
}
[DataContract()]
public class HttpJsonError
{
[DataMember(Name = "code")]
public string Code { get; set; }
[DataMember(Name = "message")]
public string Message { get; set; }
}
[DataContract()]
public class WrappedJsonError
{
[DataMember(Name = "error")]
public HttpJsonError Error { get; set; }
}
#if NETCORE
internal static class CookiesHelper
{
static readonly IGXLogger log = GXLoggerFactory.GetLogger(typeof(CookiesHelper).FullName);
internal static void PopulateCookies(this HttpRequestMessage request, CookieContainer cookieContainer)
{
if (cookieContainer != null)
{
IEnumerable<Cookie> cookies = cookieContainer.GetCookies();
if (cookies.Any())
{
request.Headers.Add("Cookie", cookies.ToHeaderFormat());
}
}
}
private static string ToHeaderFormat(this IEnumerable<Cookie> cookies)
{
return string.Join(";", cookies);
}
internal static void ExtractCookies(this HttpResponseMessage response, CookieContainer cookieContainer)
{
if (response.Headers.TryGetValues("Set-Cookie", out var cookieValues))
{
Uri uri = response.RequestMessage.RequestUri;
foreach (string cookieValue in cookieValues)
{
try
{
cookieContainer.SetCookies(uri, cookieValue);
}
catch (CookieException)
{
try
{
cookieContainer.Add(ParseCookieHeader(cookieValue));
}
catch (Exception ex2)
{
GXLogging.Warn(log, $"Ignored cookie for container: {cookieValue} url:{uri}", ex2.Message);
}
}
}
}
}
static Cookie ParseCookieHeader(string cookieHeader)
{
string[] parts = cookieHeader.Split(';', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0)
{
throw new ArgumentException("Invalid cookie header.");
}
string[] nameValuePair = parts[0].Split('=', 2);
if (nameValuePair.Length != 2)
{
throw new ArgumentException("Invalid cookie header: missing name or value.");
}
string name = nameValuePair[0];
string value = nameValuePair[1];
var cookie = new Cookie(name, value);
foreach (string part in parts[1..])
{
string[] attribute = part.Split('=', 2);
string attributeName = attribute[0].ToLowerInvariant();
if (attributeName == "path" && attribute.Length == 2)
{
cookie.Path = attribute[1];
}
else if (attributeName == "domain" && attribute.Length == 2)
{
cookie.Domain = attribute[1];
}
else if (attributeName == "secure")
{
cookie.Secure = true;
}
else if (attributeName == "httponly")
{
cookie.HttpOnly = true;
}
}
return cookie;
}
}
#endif
public class HttpHelper
{
static readonly IGXLogger log = GXLoggerFactory.GetLogger<HttpHelper>();
internal static Dictionary<string, string> GAMServices = new Dictionary<string, string>(){
{"oauth/access_token","gxoauthaccesstoken"},
{"oauth/logout","gxoauthlogout"},
{"oauth/userinfo","gxoauthuserinfo"},
{"oauth/gam/signin","agamextauthinput"},
{"oauth/gam/callback","agamextauthinput"},
{"oauth/gam/access_token","agamoauth20getaccesstoken"},
{"oauth/gam/userinfo","agamoauth20getuserinfo"},
{"oauth/gam/signout","agamextauthinput"},
{"saml/gam/callback","agamextauthinput"},
{"saml/gam/signout","agamextauthinput"},
{"oauth/requesttokenservice","agamstsauthappgetaccesstoken"},
{"oauth/queryaccesstoken","agamstsauthappvalidaccesstoken"},
{"oauth/gam/v2.0/access_token","agamoauth20getaccesstoken_v20"},
{"oauth/gam/v2.0/userinfo","agamoauth20getuserinfo_v20"},
{"oauth/gam/v2.0/requesttokenanduserinfo","agamssorestrequesttokenanduserinfo_v20"}};
internal static HashSet<string> GamServicesInternalName = new HashSet<string>(GAMServices.Values);
internal const string QUERYVIEWER_NAMESPACE = "QueryViewer.Services";
internal const string GXFLOW_NSPACE = "GXflow.Programs";
internal const string GAM_NSPACE = "GeneXus.Security.API";
/*
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
* Specifying no-cache or max-age=0 indicates that
* clients can cache a resource and must revalidate each time before using it.
* This means HTTP request occurs each time, but it can skip downloading HTTP body if the content is valid.
*/
public static string CACHE_CONTROL_HEADER_NO_CACHE = "no-cache, max-age=0";
public static string CACHE_CONTROL_HEADER_NO_CACHE_REVALIDATE = "max-age=0, no-cache, no-store, must-revalidate";
public const string ASPX = ".aspx";
public const string GXOBJECT = "/gxobject";
public const string HttpPostMethod= "POST";
public const string HttpGetMethod = "GET";
internal const string INT_FORMAT="D";
const string GAM_CODE_OTP_USER_ACCESS_CODE_SENT = "400";
const string GAM_CODE_TFA_USER_MUST_VALIDATE = "410";
const string GAM_CODE_TOKEN_EXPIRED = "103";
static Regex CapitalsToTitle = new Regex(@"(?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);
internal const string InvalidCSRFToken = "InvalidCSRFToken";
const string CORS_MAX_AGE_SECONDS = "86400";
internal static void CorsHeaders(HttpContext httpContext)
{
if (Preferences.CorsEnabled)
{
string[] origins = Preferences.CorsAllowedOrigins().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (httpContext != null)
{
string requestHeaders = httpContext.Request.Headers[HeaderNames.AccessControlRequestHeaders];
string requestMethod = httpContext.Request.Headers[HeaderNames.AccessControlRequestMethod];
CorsValuesToHeaders(httpContext.Response, origins, requestHeaders, requestMethod);
}
}
}
#if !NETCORE
internal static void CorsHeaders(HttpResponseMessageProperty response, string requestHeaders, string requestMethods)
{
if (Preferences.CorsEnabled)
{
string[] origins = Preferences.CorsAllowedOrigins().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
CorsValuesToHeaders(response, origins, requestHeaders, requestMethods);
}
}
internal static void CorsHeaders(WebOperationContext wcfContext)
{
if (Preferences.CorsEnabled)
{
string[] origins = Preferences.CorsAllowedOrigins().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (wcfContext != null)
{
string requestHeaders = wcfContext.IncomingRequest.Headers[HeaderNames.AccessControlRequestHeaders];
string requestMethods = wcfContext.IncomingRequest.Headers[HeaderNames.AccessControlRequestMethod];
CorsValuesToHeaders(wcfContext.OutgoingResponse, origins, requestHeaders, requestMethods);
}
}
}
static void CorsValuesToHeaders(OutgoingWebResponseContext httpResponse, string[] origins, string requestHeaders, string requestMethods)
{
foreach (string origin in origins)
{
if (!string.IsNullOrEmpty(origin))
httpResponse.Headers[HeaderNames.AccessControlAllowOrigin] = origin;
}
httpResponse.Headers[HeaderNames.AccessControlAllowCredentials] = bool.TrueString;
if (!string.IsNullOrEmpty(requestHeaders))
httpResponse.Headers[HeaderNames.AccessControlAllowHeaders] = StringUtil.Sanitize(requestHeaders, StringUtil.HttpHeaderWhiteList);
if (!string.IsNullOrEmpty(requestMethods))
httpResponse.Headers[HeaderNames.AccessControlAllowMethods] = StringUtil.Sanitize(requestMethods, StringUtil.HttpHeaderWhiteList);
httpResponse.Headers[HeaderNames.AccessControlMaxAge] = CORS_MAX_AGE_SECONDS;
}
static void CorsValuesToHeaders(HttpResponseMessageProperty httpResponse, string[] origins, string requestHeaders, string requestMethods)
{
foreach (string origin in origins)
{
if (!string.IsNullOrEmpty(origin))
httpResponse.Headers[HeaderNames.AccessControlAllowOrigin] = origin;
}
httpResponse.Headers[HeaderNames.AccessControlAllowCredentials] = bool.TrueString;
if (!string.IsNullOrEmpty(requestHeaders))
httpResponse.Headers[HeaderNames.AccessControlAllowHeaders] = StringUtil.Sanitize(requestHeaders, StringUtil.HttpHeaderWhiteList);
if (!string.IsNullOrEmpty(requestMethods))
httpResponse.Headers[HeaderNames.AccessControlAllowMethods] = StringUtil.Sanitize(requestMethods, StringUtil.HttpHeaderWhiteList);
httpResponse.Headers[HeaderNames.AccessControlMaxAge] = CORS_MAX_AGE_SECONDS;
}
#endif
static void CorsValuesToHeaders(HttpResponse httpResponse, string[] origins, string requestHeaders, string requestMethods)
{
//AppendHeader must be used on httpResponse (instead of httpResponse.Headers[]) to support WebDev.WevServer2
foreach (string origin in origins)
{
if (!string.IsNullOrEmpty(origin))
httpResponse.AppendHeader(HeaderNames.AccessControlAllowOrigin, origin);
}
httpResponse.AppendHeader(HeaderNames.AccessControlAllowCredentials, bool.TrueString);
if (!string.IsNullOrEmpty(requestHeaders))
httpResponse.AppendHeader(HeaderNames.AccessControlAllowHeaders, StringUtil.Sanitize(requestHeaders, StringUtil.HttpHeaderWhiteList));
if (!string.IsNullOrEmpty(requestMethods))
httpResponse.AppendHeader(HeaderNames.AccessControlAllowMethods, StringUtil.Sanitize(requestMethods, StringUtil.HttpHeaderWhiteList));
httpResponse.AppendHeader(HeaderNames.AccessControlMaxAge, CORS_MAX_AGE_SECONDS);
}
public static void SetResponseStatus(HttpContext httpContext, string statusCode, string statusDescription)
{
HttpStatusCode httpStatusCode = MapStatusCode(statusCode);
SetResponseStatus(httpContext, httpStatusCode, statusDescription);
}
public static void SetResponseStatus(HttpContext httpContext, HttpStatusCode httpStatusCode, string statusDescription)
{
#if !NETCORE
var wcfcontext = WebOperationContext.Current;
if (wcfcontext != null)
{
wcfcontext.OutgoingResponse.StatusCode = httpStatusCode;
if (httpStatusCode==HttpStatusCode.Unauthorized){
wcfcontext.OutgoingResponse.Headers.Add(HttpHeader.AUTHENTICATE_HEADER, OatuhUnauthorizedHeader(StringUtil.Sanitize(wcfcontext.IncomingRequest.Headers["Host"],StringUtil.HttpHeaderWhiteList), httpStatusCode.ToString(INT_FORMAT), string.Empty));
}
if (!string.IsNullOrEmpty(statusDescription))
wcfcontext.OutgoingResponse.StatusDescription = statusDescription.Replace(Environment.NewLine, string.Empty);
GXLogging.Error(log, String.Format("ErrCode {0}, ErrDsc {1}", httpStatusCode, statusDescription));
}
else
{
#endif
if (httpContext != null)
{
#if NETCORE
httpContext.Response.SetStatusCode((int)httpStatusCode);
#else
httpContext.Response.StatusCode = (int)httpStatusCode;
#endif
HandleUnauthorized(httpStatusCode, httpContext);
#if !NETCORE
if (!string.IsNullOrEmpty(statusDescription))
httpContext.Response.StatusDescription = statusDescription.Replace(Environment.NewLine, string.Empty);
GXLogging.Error(log, String.Format("ErrCode {0}, ErrDsc {1}", httpStatusCode, statusDescription));
}
}
#else
httpContext.SetReasonPhrase(statusDescription);
GXLogging.Error(log, String.Format("ErrCode {0}, ErrDsc {1}", httpStatusCode, statusDescription));
}
#endif
}
internal static void HandleUnauthorized(HttpStatusCode statusCode, HttpContext httpContext)
{
if (statusCode == HttpStatusCode.Unauthorized)
{
httpContext.Response.Headers[HttpHeader.AUTHENTICATE_HEADER] = HttpHelper.OatuhUnauthorizedHeader(StringUtil.Sanitize(httpContext.Request.Headers["Host"], StringUtil.HttpHeaderWhiteList), statusCode.ToString(HttpHelper.INT_FORMAT), string.Empty);
}
}
internal static HttpStatusCode MapStatusCode(string statusCode)
{
if (Enum.TryParse<HttpStatusCode>(statusCode, out HttpStatusCode result) && Enum.IsDefined(typeof(HttpStatusCode), result))
return result;
else
return HttpStatusCode.Unauthorized;
}
internal static HttpStatusCode GamCodeToHttpStatus(string code, HttpStatusCode defaultCode=HttpStatusCode.Unauthorized)
{
if (code == GAM_CODE_OTP_USER_ACCESS_CODE_SENT || code == GAM_CODE_TFA_USER_MUST_VALIDATE)
{
return HttpStatusCode.Accepted;
}
else if (code == GAM_CODE_TOKEN_EXPIRED)
{
return HttpStatusCode.Forbidden;
}
return defaultCode;
}
internal static WrappedJsonError GetJsonError(string statusCode, string statusDescription)
{
WrappedJsonError jsonError = new WrappedJsonError() { Error = new HttpJsonError() { Code = statusCode, Message = statusDescription } };
return jsonError;
}
private static void SetJsonError(HttpContext httpContext, string statusCode, string statusDescription)
{
if (httpContext != null)//<serviceHostingEnvironment aspNetCompatibilityEnabled="false" /> web.config
{
#if !NETCORE
httpContext.Response.ContentType = MediaTypesNames.ApplicationJson;
#endif
httpContext.Response.Write(JSONHelper.Serialize(GetJsonError(statusCode, statusDescription)));
}
#if !NETCORE
else
{
var wcfcontext = WebOperationContext.Current;
wcfcontext.OutgoingResponse.ContentType = MediaTypesNames.ApplicationJson;
WrappedJsonError jsonError = new WrappedJsonError() { Error = new HttpJsonError() { Code = statusCode, Message = statusDescription } };
throw new FaultException<WrappedJsonError>(jsonError, new FaultReason(statusDescription));
}
#endif
}
internal static void SetGamError(HttpContext httpContext, string code, string message, HttpStatusCode defaultCode = HttpStatusCode.Unauthorized)
{
SetResponseStatus(httpContext, GamCodeToHttpStatus(code, defaultCode), message);
SetJsonError(httpContext, code, message);
}
internal static void TraceUnexpectedError(Exception ex)
{
GXLogging.Error(log, "Error executing REST service", ex);
}
internal static void SetUnexpectedError(HttpContext httpContext, HttpStatusCode statusCode, Exception ex)
{
string statusCodeDesc = StatusCodeToTitle(statusCode);
SetUnexpectedError(httpContext, statusCode, statusCodeDesc, ex);
}
internal static void SetUnexpectedError(HttpContext httpContext, HttpStatusCode statusCode, string statusCodeDesc, Exception ex)
{
TraceUnexpectedError(ex);
string statusCodeStr = statusCode.ToString(INT_FORMAT);
SetResponseStatus(httpContext, statusCode, statusCodeDesc);
SetJsonError(httpContext, statusCodeStr, statusCodeDesc);
}
#if NETCORE
internal static WrappedJsonError HandleUnexpectedError(HttpContext httpContext, HttpStatusCode statusCode, Exception ex)
{
string statusCodeDesc = StatusCodeToTitle(statusCode);
TraceUnexpectedError(ex);
string statusCodeStr = statusCode.ToString(HttpHelper.INT_FORMAT);
HandleUnauthorized(statusCode, httpContext);
httpContext.SetReasonPhrase(statusCodeDesc);
GXLogging.Error(log, String.Format("ErrCode {0}, ErrDsc {1}", statusCode, statusCodeDesc));
return new WrappedJsonError() { Error = new HttpJsonError() { Code = statusCodeStr, Message = statusCodeDesc } };
}
#endif
internal static string StatusCodeToTitle(HttpStatusCode statusCode)
{
return CapitalsToTitle.Replace(statusCode.ToString(), " ");
}
internal static void SetError(HttpContext httpContext, string statusCode, string statusDescription)
{
SetResponseStatus(httpContext, statusCode, statusDescription);
SetJsonError(httpContext, statusCode, statusDescription);
}
internal static String OatuhUnauthorizedHeader(string realm, string errCode, string errDescription)
{
if (string.IsNullOrEmpty(errDescription))
return String.Format("OAuth realm=\"{0}\"", realm);
else
return string.Format("OAuth realm=\"{0}\",error_code=\"{1}\",error_description=\"{2}\"", realm, errCode, errDescription);
}
public static string GetHttpRequestPostedFileType(HttpContext httpContext, string varName)
{
try
{
var pf = GetFormFile(httpContext, varName);
if (pf != null)
return FileUtil.GetFileType(pf.FileName);
}
catch { }
return string.Empty;
}
#if NETCORE
public static IFormFile GetFormFile(HttpContext httpContext, String varName)
{
return httpContext.Request.Form.Files[varName];
}
#else
public static HttpPostedFile GetFormFile(HttpContext httpContext, String varName)
{
return httpContext.Request.Files[varName];
}
#endif
public static string GetHttpRequestPostedFileName(HttpContext httpContext, string varName)
{
try
{
var pf = GetFormFile(httpContext, varName);
if (pf != null)
return FileUtil.GetFileName(pf.FileName);
}
catch { }
return string.Empty;
}
public static bool GetHttpRequestPostedFile(IGxContext gxContext, string varName, out string filePath)
{
filePath = null;
var httpContext = gxContext.HttpContext;
if (httpContext != null)
{
var pf = GetFormFile(httpContext, varName);
if (pf != null)
{
string tempDir = Preferences.getTMP_MEDIA_PATH();
string ext = Path.GetExtension(pf.FileName);
if (ext != null)
ext = ext.TrimStart('.');
filePath = FileUtil.getTempFileName(tempDir);
GXLogging.Debug(log, "cgiGet(" + varName + "), fileName:" + filePath);
GxFile file = new GxFile(tempDir, filePath, GxFileType.PrivateAttribute);
#if NETCORE
filePath = file.Create(pf.OpenReadStream());
#else
filePath = file.Create(pf.InputStream);
#endif
GXFileWatcher.Instance.AddTemporaryFile(file, gxContext);
return true;
}
}
return false;
}
public static string RequestPhysicalApplicationPath(HttpContext context = null)
{
#if NETCORE
if (GxContext.IsAzureContext)
return FileUtil.GetStartupDirectory();
return Directory.GetParent(FileUtil.GetStartupDirectory()).FullName;
#else
if (context==null)
return HttpContext.Current.Request.PhysicalApplicationPath;
else
return context.Request.PhysicalApplicationPath;
#endif
}
#if NETCORE
public static byte[] DownloadFile(string url, out HttpStatusCode statusCode)
{
byte[] buffer = Array.Empty<byte>();
HttpClient httpClient = GxHttpClient.GetHttpClientInstance(new Uri(url), out bool disposableInstance);
try
{
using (HttpResponseMessage response = httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).Result)
{
if (response.IsSuccessStatusCode)
{
statusCode = HttpStatusCode.OK;
using (HttpContent content = response.Content)
{
return content.ReadAsByteArrayAsync().Result;
}
}
else
{
statusCode = response.StatusCode;
}
}
}
finally
{
if (disposableInstance)
httpClient.Dispose();
}
return buffer;
}
#else
public static byte[] DownloadFile(string fileName, out HttpStatusCode statusCode)
{
byte[] binary = Array.Empty<byte>();
try
{
WebClient Client = new WebClient();
if (!string.IsNullOrEmpty(Preferences.HttpClientUserAgent))
Client.Headers.Add(HttpHeader.USER_AGENT, Preferences.HttpClientUserAgent);
binary = Client.DownloadData(fileName);
statusCode = HttpStatusCode.OK;
}
catch (WebException e) //An error occurred while downloading data.
{
if (e.Response != null)
{
statusCode = ((HttpWebResponse)e.Response).StatusCode;
}
else
{
statusCode = HttpStatusCode.InternalServerError;
}
GXLogging.Error(log, "An error occurred while downloading data from url " + fileName + " " + e.Message, e);
}
return binary;
}
#endif
static bool NamedParametersQuery(string query)
{
return Preferences.UseNamedParameters && query.Contains("=");
}
public static string[] GetParameterValues(string query)
{
if (NamedParametersQuery(query))
{
NameValueCollection names = HttpUtility.ParseQueryString(query);
string[] values = new string[names.Count];
for (int i = 0; i < names.Count; i++)
values[i] = names[i];
return values;
}
else
{
return query.Split(',');
}
}
internal static void AllowHeader(HttpContext httpContext, List<string> methods)
{
httpContext.Response.AppendHeader(HeaderNames.Allow, string.Join(",", methods));
}
internal static string HtmlEncodeJsonValue(string value)
{
return GXUtil.HtmlEncodeInputValue(JsonQuote(value));
}
static void AppendCharAsUnicodeJavaScript(StringBuilder builder, char c)
{
builder.Append("\\u");
int num = c;
builder.Append(num.ToString("x4", CultureInfo.InvariantCulture));
}
/**
* Produce a string in double quotes with backslash sequences in all the
* right places. A backslash will be inserted within </, allowing JSON
* text to be delivered in HTML. In JSON text, a string cannot contain a
* control character or an unescaped quote or backslash.
* */
internal static string JsonQuote(string value, bool addDoubleQuotes=false)
{
string text = string.Empty;
if (!string.IsNullOrEmpty(value))
{
int i;
int len = value.Length;
StringBuilder sb = new StringBuilder(len + 4);
for (i = 0; i < len; i += 1)
{
char c = value[i];
switch (c)
{
case '\\':
case '"':
sb.Append('\\');
sb.Append(c);
break;
case '\b':
sb.Append("\\b");
break;
case '\t':
sb.Append("\\t");
break;
case '\n':
sb.Append("\\n");
break;
case '\f':
sb.Append("\\f");
break;
case '\r':
sb.Append("\\r");
break;
default:
{
if (c < ' ')
{
AppendCharAsUnicodeJavaScript(sb, c);
}
else
{
sb.Append(c);
}
}
break;
}
}
text = sb.ToString();
}
if (!addDoubleQuotes)
{
return text;
}
else
{
return "\"" + text + "\"";
}
}
#if !NETCORE
public static void SetSoapContext(GXSOAPContext value)
{
if (OperationContext.Current != null)
{
RequestMessageExtension ext = OperationContext.Current.Extensions.Find<RequestMessageExtension>();
if (ext == null)
{
ext = new RequestMessageExtension();
OperationContext.Current.Extensions.Add(ext);
}
ext.SOAPContext = value;
}
}
internal static GXSOAPContext GetSoapContext()
{
if (OperationContext.Current != null)
{
RequestMessageExtension ext = OperationContext.Current.Extensions.Find<RequestMessageExtension>();
if (ext != null)
{
return ext.SOAPContext;
}
}
return null;
}
#endif
}
#if NETCORE
public class HttpCookieCollection : Dictionary<string, HttpCookie>
{
public new HttpCookie this[string key] {
get {
if (this.ContainsKey(key))
return base[key];
else
return null;
}
set
{
base[key] = value;
}
}
}
public sealed class HttpCookie
{
//
// Summary:
// Creates and names a new cookie.
//
// Parameters:
// name:
// The name of the new cookie.
public HttpCookie(string name){
Name = name;
}
//
// Summary:
// Creates, names, and assigns a value to a new cookie.
//
// Parameters:
// name:
// The name of the new cookie.
//
// value:
// The value of the new cookie.
public HttpCookie(string name, string value)
{
Name = name;
Value = value;
}
//
// Summary:
// Gets or sets the domain to associate the cookie with.
//
// Returns:
// The name of the domain to associate the cookie with. The default value is the
// current domain.
public string Domain { get; set; }
//
// Summary:
// Gets or sets the expiration date and time for the cookie.
//
// Returns:
// The time of day (on the client) at which the cookie expires.
public DateTime Expires { get; set; }
//
// Summary:
// Gets a value indicating whether a cookie has subkeys.
//
// Returns:
// true if the cookie has subkeys, otherwise, false. The default value is false.
public bool HasKeys { get; }
//
// Summary:
// Gets or sets a value that specifies whether a cookie is accessible by client-side
// script.
//
// Returns:
// true if the cookie has the HttpOnly attribute and cannot be accessed through
// a client-side script; otherwise, false. The default is false.
public bool HttpOnly { get; set; }
//
// Summary:
// Gets or sets the name of a cookie.
//
// Returns:
// The default value is a null reference (Nothing in Visual Basic) unless the constructor
// specifies otherwise.
public string Name { get; set; }
//
// Summary:
// Gets or sets the virtual path to transmit with the current cookie.
//
// Returns:
// The virtual path to transmit with the cookie. The default is /, which is the
// server root.
public string Path { get; set; }
//
// Summary:
// Gets or sets a value indicating whether to transmit the cookie using Secure Sockets
// Layer (SSL)--that is, over HTTPS only.
//
// Returns:
// true to transmit the cookie over an SSL connection (HTTPS); otherwise, false.
// The default value is false.
public bool Secure { get; set; }
//
// Summary:
// Gets or sets an individual cookie value.
//
// Returns:
// The value of the cookie. The default value is a null reference (Nothing in Visual
// Basic).
public string Value { get; set; }
}
public static class HttpResponseExtensions
{
public static void AppendHeader(this HttpResponse response, string name, string value) {
if (!response.HasStarted)
response.Headers[name] = value;
}
public static void AddHeader(this HttpResponse response, string name, string value)
{
if (!response.HasStarted)
response.Headers[name] = value;
}
public static void Write(this HttpResponse response, string value)
{
//response.WriteAsync(value).Wait();//Unsupported by GxHttpAzureResponse
response.Body.Write(Encoding.UTF8.GetBytes(value));
}
public static void WriteFile(this HttpResponse response, string fileName)
{
response.SendFileAsync(fileName).Wait();
}
public static void SetStatusCode(this HttpResponse response, int value)
{
if (!response.HasStarted)
response.StatusCode = value;
}
}
#endif
public static class HttpWebRequestExtensions
{
public static void SetReferer(this HttpWebRequest request, string referer)
{
#if NETCORE
request.Headers["Referer"] = referer;
#else
request.Referer = referer;
#endif
}
public static void SetUserAgent(this HttpWebRequest request, string userAgent)
{
#if NETCORE
request.Headers["User-agent"] = userAgent;
#else
request.UserAgent = userAgent;
#endif
}
public static void SetExpect(this HttpWebRequest request, string expect)
{
#if NETCORE
request.Headers["Expect"] = expect;
#else
request.Expect = expect;
#endif
}
public static void SetKeepAlive(this HttpWebRequest request, bool keepAlive)
{
#if NETCORE
if (keepAlive)
request.Headers["Connection"] = "Keep-Alive";
else
request.Headers["Connection"] = "Close";
#else
request.KeepAlive = keepAlive;
#endif
}
}
public static class HttpContextExtensions
{
#if NETCORE
internal static string NEWSESSION = "GXNEWSESSION";
public static void NewSessionCheck(this HttpContext context)
{
GxWebSession websession = new GxWebSession(new HttpSessionState(context.Session));
string value = websession.Get<string>(NEWSESSION);
if (string.IsNullOrEmpty(value))
{
websession.Set<string>(NEWSESSION, bool.TrueString);
}
else
{
websession.Set<string>(NEWSESSION, bool.FalseString);
}
}
public static bool IsNewSession(this HttpContext context)
{
GxWebSession websession = new GxWebSession(new HttpSessionState(context.Session));
string value=websession.Get<string>(NEWSESSION);
return string.IsNullOrEmpty(value) || value == bool.TrueString;
}
#else
public static bool IsNewSession(this HttpContext context)
{
return context.Session.IsNewSession;
}
#endif
internal static string GetServerMachineName(this HttpContext context)
{
#if NETCORE
IPAddress address = context.Connection.LocalIpAddress;
if (address!=null)
{
if (address.IsIPv4MappedToIPv6)
return address.MapToIPv4().ToString();
else
return address.ToString();
}
else
return string.Empty;
#else
return context.Server.MachineName;
#endif
}
public static string GetUserHostAddress(this HttpContext context)
{
#if NETCORE
IPAddress address = context.Connection.RemoteIpAddress;
if (address != null)
{
if (address.IsIPv4MappedToIPv6)
return address.MapToIPv4().ToString();
else
return address.ToString();
}
else
return string.Empty;
#else
return context.Request.UserHostAddress;
#endif
}
public static void SetReasonPhrase(this HttpContext context, string statusDescription)
{
#if NETCORE
if (!string.IsNullOrEmpty(statusDescription) && !context.Response.HasStarted)
context.Features.Get<IHttpResponseFeature>().ReasonPhrase = statusDescription.Replace(Environment.NewLine, string.Empty);
#else
context.Response.StatusDescription = statusDescription;
#endif
}
#if NETCORE
internal static async Task CommitSessionAsync(this HttpContext context)
{
if (context.Items.TryGetValue(HttpSyncSessionState.CTX_SESSION, out object ctxSession))
{
var _contextSession = ctxSession as Dictionary<string, string>;
if (_contextSession != null && _contextSession.Count > 0)
{
ISession _httpSession = context.Session;
var semaphore = LockTracker.Get(_httpSession.Id);
await semaphore.WaitAsync();
try
{
FieldInfo loaded = _httpSession.GetType().GetField("_loaded", BindingFlags.Instance | BindingFlags.NonPublic);
if (loaded != null)
{
loaded.SetValue(_httpSession, false);
await _httpSession.LoadAsync();
}
foreach (string s in _contextSession.Keys)
{
if (_contextSession[s] == null)
_httpSession.Remove(s);
else
_httpSession.SetString(s, _contextSession[s]);
}
context.Items.Remove(HttpSyncSessionState.CTX_SESSION);