mscorlib(4.0.0.0) API with additions
HttpWebRequest.cs
4 using System.IO;
5 using System.Net.Cache;
7 using System.Net.Security;
8 using System.Reflection;
11 using System.Security;
14 using System.Text;
15 using System.Threading;
16 
17 namespace System.Net
18 {
20  [Serializable]
21  [FriendAccessAllowed]
22  [global::__DynamicallyInvokable]
24  {
25  private static class AbortState
26  {
27  public const int Public = 1;
28 
29  public const int Internal = 2;
30  }
31 
32  [Flags]
33  private enum Booleans : uint
34  {
35  AllowAutoRedirect = 0x1,
37  ExpectContinue = 0x4,
38  ProxySet = 0x10,
40  IsVersionHttp10 = 0x80,
41  SendChunked = 0x100,
42  EnableDecompression = 0x200,
43  IsTunnelRequest = 0x400,
44  IsWebSocketRequest = 0x800,
45  Default = 0x7
46  }
47 
48  private bool m_Saw100Continue;
49 
50  private bool m_KeepAlive = true;
51 
52  private bool m_LockConnection;
53 
54  private bool m_NtlmKeepAlive;
55 
56  private bool m_PreAuthenticate;
57 
58  private DecompressionMethods m_AutomaticDecompression;
59 
60  private int m_Aborted;
61 
62  private bool m_OnceFailed;
63 
64  private bool m_Pipelined = true;
65 
66  private bool m_Retry = true;
67 
68  private bool m_HeadersCompleted;
69 
70  private bool m_IsCurrentAuthenticationStateProxy;
71 
72  private bool m_NeedsToReadForResponse = true;
73 
74  private bool m_BodyStarted;
75 
76  private bool m_RequestSubmitted;
77 
78  private bool m_OriginallyBuffered;
79 
80  private bool m_Extra401Retry;
81 
82  private long m_StartTimestamp;
83 
84  internal const HttpStatusCode MaxOkStatus = (HttpStatusCode)299;
85 
86  private const HttpStatusCode MaxRedirectionStatus = (HttpStatusCode)399;
87 
88  private const int RequestLineConstantSize = 12;
89 
90  private const string ContinueHeader = "100-continue";
91 
92  internal const string ChunkedHeader = "chunked";
93 
94  internal const string GZipHeader = "gzip";
95 
96  internal const string DeflateHeader = "deflate";
97 
98  internal const int DefaultReadWriteTimeout = 300000;
99 
100  internal const int DefaultContinueTimeout = 350;
101 
102  private static readonly byte[] HttpBytes = new byte[5]
103  {
104  72,
105  84,
106  84,
107  80,
108  47
109  };
110 
111  private static readonly WaitCallback s_EndWriteHeaders_Part2Callback = EndWriteHeaders_Part2Wrapper;
112 
113  private static readonly TimerThread.Callback s_ContinueTimeoutCallback = ContinueTimeoutCallback;
114 
115  private static readonly TimerThread.Queue s_ContinueTimerQueue = TimerThread.GetOrCreateQueue(350);
116 
117  private static readonly TimerThread.Callback s_TimeoutCallback = TimeoutCallback;
118 
119  private static readonly WaitCallback s_AbortWrapper = AbortWrapper;
120 
121  private static int s_UniqueGroupId;
122 
123  private Booleans _Booleans = Booleans.Default;
124 
125  private TimerThread.Timer m_ContinueTimer;
126 
127  private InterlockedGate m_ContinueGate;
128 
129  private int m_ContinueTimeout;
130 
131  private TimerThread.Queue m_ContinueTimerQueue;
132 
133  private object m_PendingReturnResult;
134 
135  private LazyAsyncResult _WriteAResult;
136 
137  private LazyAsyncResult _ReadAResult;
138 
139  private LazyAsyncResult _ConnectionAResult;
140 
141  private LazyAsyncResult _ConnectionReaderAResult;
142 
143  private TriState _RequestIsAsync;
144 
145  private HttpContinueDelegate _ContinueDelegate;
146 
147  internal ServicePoint _ServicePoint;
148 
149  internal HttpWebResponse _HttpResponse;
150 
151  private object _CoreResponse;
152 
153  private int _NestedWriteSideCheck;
154 
155  private KnownHttpVerb _Verb;
156 
157  private KnownHttpVerb _OriginVerb;
158 
159  private bool _HostHasPort;
160 
161  private Uri _HostUri;
162 
163  private WebHeaderCollection _HttpRequestHeaders;
164 
165  private byte[] _WriteBuffer;
166 
167  private int _WriteBufferLength;
168 
169  private const int CachedWriteBufferSize = 512;
170 
171  private static PinnableBufferCache _WriteBufferCache = new PinnableBufferCache("System.Net.HttpWebRequest", 512);
172 
173  private bool _WriteBufferFromPinnableCache;
174 
175  private HttpWriteMode _HttpWriteMode;
176 
177  private Uri _Uri;
178 
179  private Uri _OriginUri;
180 
181  private string _MediaType;
182 
183  private long _ContentLength;
184 
185  private IWebProxy _Proxy;
186 
187  private ProxyChain _ProxyChain;
188 
189  private string _ConnectionGroupName;
190 
191  private bool m_InternalConnectionGroup;
192 
193  private AuthenticationState _ProxyAuthenticationState;
194 
195  private AuthenticationState _ServerAuthenticationState;
196 
197  private ICredentials _AuthInfo;
198 
199  private HttpAbortDelegate _AbortDelegate;
200 
201  private ConnectStream _SubmitWriteStream;
202 
203  private ConnectStream _OldSubmitWriteStream;
204 
205  private int _MaximumAllowedRedirections;
206 
207  private int _AutoRedirects;
208 
209  private bool _RedirectedToDifferentHost;
210 
211  private int _RerequestCount;
212 
213  private int _Timeout;
214 
215  private TimerThread.Timer _Timer;
216 
217  private TimerThread.Queue _TimerQueue;
218 
219  private int _RequestContinueCount;
220 
221  private int _ReadWriteTimeout;
222 
223  private CookieContainer _CookieContainer;
224 
225  private int _MaximumResponseHeadersLength;
226 
227  private UnlockConnectionDelegate _UnlockDelegate;
228 
229  private bool _returnResponseOnFailureStatusCode;
230 
231  private Action<Stream> _resendRequestContent;
232 
233  private long _originalContentLength;
234 
235  private X509CertificateCollection _ClientCertificates;
236 
237  [FriendAccessAllowed]
238  internal RtcState RtcState
239  {
240  get;
241  set;
242  }
243 
244  internal TimerThread.Timer RequestTimer => _Timer;
245 
246  internal bool Aborted => m_Aborted != 0;
247 
251  public virtual bool AllowAutoRedirect
252  {
253  get
254  {
255  return (_Booleans & Booleans.AllowAutoRedirect) != (Booleans)0u;
256  }
257  set
258  {
259  if (value)
260  {
261  _Booleans |= Booleans.AllowAutoRedirect;
262  }
263  else
264  {
265  _Booleans &= ~Booleans.AllowAutoRedirect;
266  }
267  }
268  }
269 
273  public virtual bool AllowWriteStreamBuffering
274  {
275  get
276  {
277  return (_Booleans & Booleans.AllowWriteStreamBuffering) != (Booleans)0u;
278  }
279  set
280  {
281  if (value)
282  {
283  _Booleans |= Booleans.AllowWriteStreamBuffering;
284  }
285  else
286  {
287  _Booleans &= ~Booleans.AllowWriteStreamBuffering;
288  }
289  }
290  }
291 
296  [global::__DynamicallyInvokable]
297  public virtual bool AllowReadStreamBuffering
298  {
299  [global::__DynamicallyInvokable]
300  get
301  {
302  return false;
303  }
304  [global::__DynamicallyInvokable]
305  set
306  {
307  if (value)
308  {
309  throw new InvalidOperationException(SR.GetString("NotSupported"));
310  }
311  }
312  }
313 
314  private bool ExpectContinue
315  {
316  get
317  {
318  return (_Booleans & Booleans.ExpectContinue) != (Booleans)0u;
319  }
320  set
321  {
322  if (value)
323  {
324  _Booleans |= Booleans.ExpectContinue;
325  }
326  else
327  {
328  _Booleans &= ~Booleans.ExpectContinue;
329  }
330  }
331  }
332 
336  [global::__DynamicallyInvokable]
337  public virtual bool HaveResponse
338  {
339  [global::__DynamicallyInvokable]
340  get
341  {
342  if (_ReadAResult != null)
343  {
344  return _ReadAResult.InternalPeekCompleted;
345  }
346  return false;
347  }
348  }
349 
350  internal bool NtlmKeepAlive
351  {
352  get
353  {
354  return m_NtlmKeepAlive;
355  }
356  set
357  {
358  m_NtlmKeepAlive = value;
359  }
360  }
361 
362  internal bool NeedsToReadForResponse
363  {
364  get
365  {
366  return m_NeedsToReadForResponse;
367  }
368  set
369  {
370  m_NeedsToReadForResponse = value;
371  }
372  }
373 
374  internal bool BodyStarted => m_BodyStarted;
375 
379  public bool KeepAlive
380  {
381  get
382  {
383  return m_KeepAlive;
384  }
385  set
386  {
387  m_KeepAlive = value;
388  }
389  }
390 
391  internal bool LockConnection
392  {
393  get
394  {
395  return m_LockConnection;
396  }
397  set
398  {
399  m_LockConnection = value;
400  }
401  }
402 
406  public bool Pipelined
407  {
408  get
409  {
410  return m_Pipelined;
411  }
412  set
413  {
414  m_Pipelined = value;
415  }
416  }
417 
421  public override bool PreAuthenticate
422  {
423  get
424  {
425  return m_PreAuthenticate;
426  }
427  set
428  {
429  m_PreAuthenticate = value;
430  }
431  }
432 
433  private bool ProxySet
434  {
435  get
436  {
437  return (_Booleans & Booleans.ProxySet) != (Booleans)0u;
438  }
439  set
440  {
441  if (value)
442  {
443  _Booleans |= Booleans.ProxySet;
444  }
445  else
446  {
447  _Booleans &= ~Booleans.ProxySet;
448  }
449  }
450  }
451 
452  private bool RequestSubmitted => m_RequestSubmitted;
453 
454  internal bool Saw100Continue
455  {
456  get
457  {
458  return m_Saw100Continue;
459  }
460  set
461  {
462  m_Saw100Continue = value;
463  }
464  }
465 
470  {
471  get
472  {
473  return (_Booleans & Booleans.UnsafeAuthenticatedConnectionSharing) != (Booleans)0u;
474  }
475  set
476  {
477  ExceptionHelper.WebPermissionUnrestricted.Demand();
478  if (value)
479  {
480  _Booleans |= Booleans.UnsafeAuthenticatedConnectionSharing;
481  }
482  else
483  {
484  _Booleans &= ~Booleans.UnsafeAuthenticatedConnectionSharing;
485  }
486  }
487  }
488 
489  internal bool UnsafeOrProxyAuthenticatedConnectionSharing
490  {
491  get
492  {
493  if (!m_IsCurrentAuthenticationStateProxy)
494  {
496  }
497  return true;
498  }
499  }
500 
501  private bool IsVersionHttp10
502  {
503  get
504  {
505  return (_Booleans & Booleans.IsVersionHttp10) != (Booleans)0u;
506  }
507  set
508  {
509  if (value)
510  {
511  _Booleans |= Booleans.IsVersionHttp10;
512  }
513  else
514  {
515  _Booleans &= ~Booleans.IsVersionHttp10;
516  }
517  }
518  }
519 
524  public bool SendChunked
525  {
526  get
527  {
528  return (_Booleans & Booleans.SendChunked) != (Booleans)0u;
529  }
530  set
531  {
532  if (RequestSubmitted)
533  {
534  throw new InvalidOperationException(SR.GetString("net_writestarted"));
535  }
536  if (value)
537  {
538  _Booleans |= Booleans.SendChunked;
539  }
540  else
541  {
542  _Booleans &= ~Booleans.SendChunked;
543  }
544  }
545  }
546 
551  {
552  get
553  {
554  return m_AutomaticDecompression;
555  }
556  set
557  {
558  if (RequestSubmitted)
559  {
560  throw new InvalidOperationException(SR.GetString("net_writestarted"));
561  }
562  m_AutomaticDecompression = value;
563  }
564  }
565 
566  internal HttpWriteMode HttpWriteMode
567  {
568  get
569  {
570  return _HttpWriteMode;
571  }
572  set
573  {
574  _HttpWriteMode = value;
575  }
576  }
577 
580  public new static RequestCachePolicy DefaultCachePolicy
581  {
582  get
583  {
584  RequestCachePolicy policy = RequestCacheManager.GetBinding(Uri.UriSchemeHttp).Policy;
585  if (policy == null)
586  {
588  }
589  return policy;
590  }
591  set
592  {
593  ExceptionHelper.WebPermissionUnrestricted.Demand();
594  RequestCacheBinding binding = RequestCacheManager.GetBinding(Uri.UriSchemeHttp);
595  RequestCacheManager.SetBinding(Uri.UriSchemeHttp, new RequestCacheBinding(binding.Cache, binding.Validator, value));
596  }
597  }
598 
602  public static int DefaultMaximumResponseHeadersLength
603  {
604  get
605  {
606  return SettingsSectionInternal.Section.MaximumResponseHeadersLength;
607  }
608  set
609  {
610  ExceptionHelper.WebPermissionUnrestricted.Demand();
611  if (value < 0 && value != -1)
612  {
613  throw new ArgumentOutOfRangeException("value", SR.GetString("net_toosmall"));
614  }
615  SettingsSectionInternal.Section.MaximumResponseHeadersLength = value;
616  }
617  }
618 
622  public static int DefaultMaximumErrorResponseLength
623  {
624  get
625  {
626  return SettingsSectionInternal.Section.MaximumErrorResponseLength;
627  }
628  set
629  {
630  ExceptionHelper.WebPermissionUnrestricted.Demand();
631  if (value < 0 && value != -1)
632  {
633  throw new ArgumentOutOfRangeException("value", SR.GetString("net_toosmall"));
634  }
635  SettingsSectionInternal.Section.MaximumErrorResponseLength = value;
636  }
637  }
638 
644  {
645  get
646  {
647  return _MaximumResponseHeadersLength;
648  }
649  set
650  {
651  if (RequestSubmitted)
652  {
653  throw new InvalidOperationException(SR.GetString("net_reqsubmitted"));
654  }
655  if (value < 0 && value != -1)
656  {
657  throw new ArgumentOutOfRangeException("value", SR.GetString("net_toosmall"));
658  }
659  _MaximumResponseHeadersLength = value;
660  }
661  }
662 
663  internal HttpAbortDelegate AbortDelegate
664  {
665  set
666  {
667  _AbortDelegate = value;
668  }
669  }
670 
671  internal LazyAsyncResult ConnectionAsyncResult => _ConnectionAResult;
672 
673  internal LazyAsyncResult ConnectionReaderAsyncResult => _ConnectionReaderAResult;
674 
675  internal bool UserRetrievedWriteStream
676  {
677  get
678  {
679  if (_WriteAResult != null)
680  {
681  return _WriteAResult.InternalPeekCompleted;
682  }
683  return false;
684  }
685  }
686 
687  private bool IsOutstandingGetRequestStream
688  {
689  get
690  {
691  if (_WriteAResult != null)
692  {
693  return !_WriteAResult.InternalPeekCompleted;
694  }
695  return false;
696  }
697  }
698 
699  internal bool Async
700  {
701  get
702  {
703  return _RequestIsAsync != TriState.False;
704  }
705  set
706  {
707  if (_RequestIsAsync == TriState.Unspecified)
708  {
709  _RequestIsAsync = (value ? TriState.True : TriState.False);
710  }
711  }
712  }
713 
714  internal UnlockConnectionDelegate UnlockConnectionDelegate
715  {
716  get
717  {
718  return _UnlockDelegate;
719  }
720  set
721  {
722  _UnlockDelegate = value;
723  }
724  }
725 
726  private bool UsesProxy => ServicePoint.InternalProxyServicePoint;
727 
728  internal HttpStatusCode ResponseStatusCode => _HttpResponse.StatusCode;
729 
730  internal bool UsesProxySemantics
731  {
732  get
733  {
734  if (ServicePoint.InternalProxyServicePoint)
735  {
736  if ((object)_Uri.Scheme == Uri.UriSchemeHttps || IsWebSocketRequest)
737  {
738  return IsTunnelRequest;
739  }
740  return true;
741  }
742  return false;
743  }
744  }
745 
746  internal Uri ChallengedUri => CurrentAuthenticationState.ChallengedUri;
747 
748  internal AuthenticationState ProxyAuthenticationState
749  {
750  get
751  {
752  if (_ProxyAuthenticationState == null)
753  {
754  _ProxyAuthenticationState = new AuthenticationState(isProxyAuth: true);
755  }
756  return _ProxyAuthenticationState;
757  }
758  }
759 
760  internal AuthenticationState ServerAuthenticationState
761  {
762  get
763  {
764  if (_ServerAuthenticationState == null)
765  {
766  _ServerAuthenticationState = new AuthenticationState(isProxyAuth: false);
767  }
768  return _ServerAuthenticationState;
769  }
770  set
771  {
772  _ServerAuthenticationState = value;
773  }
774  }
775 
776  internal AuthenticationState CurrentAuthenticationState
777  {
778  get
779  {
780  if (!m_IsCurrentAuthenticationStateProxy)
781  {
782  return _ServerAuthenticationState;
783  }
784  return _ProxyAuthenticationState;
785  }
786  set
787  {
788  m_IsCurrentAuthenticationStateProxy = (_ProxyAuthenticationState == value);
789  }
790  }
791 
796  {
797  get
798  {
799  if (_ClientCertificates == null)
800  {
801  _ClientCertificates = new X509CertificateCollection();
802  }
803  return _ClientCertificates;
804  }
805  set
806  {
807  if (value == null)
808  {
809  throw new ArgumentNullException("value");
810  }
811  _ClientCertificates = value;
812  }
813  }
814 
817  [global::__DynamicallyInvokable]
818  public virtual CookieContainer CookieContainer
819  {
820  [global::__DynamicallyInvokable]
821  get
822  {
823  return _CookieContainer;
824  }
825  [global::__DynamicallyInvokable]
826  set
827  {
828  _CookieContainer = value;
829  }
830  }
831 
836  [global::__DynamicallyInvokable]
837  public virtual bool SupportsCookieContainer
838  {
839  [global::__DynamicallyInvokable]
840  get
841  {
842  return true;
843  }
844  }
845 
848  [global::__DynamicallyInvokable]
849  public override Uri RequestUri
850  {
851  [global::__DynamicallyInvokable]
852  get
853  {
854  return _OriginUri;
855  }
856  }
857 
862  public override long ContentLength
863  {
864  get
865  {
866  return _ContentLength;
867  }
868  set
869  {
870  if (RequestSubmitted)
871  {
872  throw new InvalidOperationException(SR.GetString("net_writestarted"));
873  }
874  if (value < 0)
875  {
876  throw new ArgumentOutOfRangeException("value", SR.GetString("net_clsmall"));
877  }
878  _ContentLength = value;
879  _originalContentLength = value;
880  }
881  }
882 
886  public override int Timeout
887  {
888  get
889  {
890  return _Timeout;
891  }
892  set
893  {
894  if (value < 0 && value != -1)
895  {
896  throw new ArgumentOutOfRangeException("value", SR.GetString("net_io_timeout_use_ge_zero"));
897  }
898  if (_Timeout != value)
899  {
900  _Timeout = value;
901  _TimerQueue = null;
902  }
903  }
904  }
905 
906  private TimerThread.Queue TimerQueue
907  {
908  get
909  {
910  TimerThread.Queue queue = _TimerQueue;
911  if (queue == null)
912  {
913  queue = (_TimerQueue = TimerThread.GetOrCreateQueue((_Timeout == 0) ? 1 : _Timeout));
914  }
915  return queue;
916  }
917  }
918 
923  public int ReadWriteTimeout
924  {
925  get
926  {
927  return _ReadWriteTimeout;
928  }
929  set
930  {
931  if (RequestSubmitted)
932  {
933  throw new InvalidOperationException(SR.GetString("net_reqsubmitted"));
934  }
935  if (value <= 0 && value != -1)
936  {
937  throw new ArgumentOutOfRangeException("value", SR.GetString("net_io_timeout_use_gt_zero"));
938  }
939  _ReadWriteTimeout = value;
940  }
941  }
942 
945  [global::__DynamicallyInvokable]
946  public int ContinueTimeout
947  {
948  [global::__DynamicallyInvokable]
949  get
950  {
951  return m_ContinueTimeout;
952  }
953  [global::__DynamicallyInvokable]
954  set
955  {
956  if (RequestSubmitted)
957  {
958  throw new InvalidOperationException(SR.GetString("net_reqsubmitted"));
959  }
960  if (value < 0 && value != -1)
961  {
962  throw new ArgumentOutOfRangeException("value", SR.GetString("net_io_timeout_use_ge_zero"));
963  }
964  if (m_ContinueTimeout != value)
965  {
966  m_ContinueTimeout = value;
967  if (value == 350)
968  {
969  m_ContinueTimerQueue = s_ContinueTimerQueue;
970  }
971  else
972  {
973  m_ContinueTimerQueue = null;
974  }
975  }
976  }
977  }
978 
979  private TimerThread.Queue ContinueTimerQueue
980  {
981  get
982  {
983  if (m_ContinueTimerQueue == null)
984  {
985  m_ContinueTimerQueue = TimerThread.GetOrCreateQueue((m_ContinueTimeout == 0) ? 1 : m_ContinueTimeout);
986  }
987  return m_ContinueTimerQueue;
988  }
989  }
990 
991  internal bool HeadersCompleted
992  {
993  get
994  {
995  return m_HeadersCompleted;
996  }
997  set
998  {
999  m_HeadersCompleted = value;
1000  }
1001  }
1002 
1003  private bool CanGetRequestStream => !CurrentMethod.ContentBodyNotAllowed;
1004 
1005  internal bool CanGetResponseStream => !CurrentMethod.ExpectNoContentResponse;
1006 
1007  internal bool RequireBody => CurrentMethod.RequireContentBody;
1008 
1009  internal bool HasEntityBody
1010  {
1011  get
1012  {
1013  if (HttpWriteMode != HttpWriteMode.Chunked && HttpWriteMode != HttpWriteMode.Buffer)
1014  {
1015  if (HttpWriteMode == HttpWriteMode.ContentLength)
1016  {
1017  return ContentLength > 0;
1018  }
1019  return false;
1020  }
1021  return true;
1022  }
1023  }
1024 
1027  public Uri Address => _Uri;
1028 
1032  {
1033  get
1034  {
1035  return _ContinueDelegate;
1036  }
1037  set
1038  {
1039  _ContinueDelegate = value;
1040  }
1041  }
1042 
1045  public ServicePoint ServicePoint => FindServicePoint(forceFind: false);
1046 
1052  public string Host
1053  {
1054  get
1055  {
1056  if (UseCustomHost)
1057  {
1058  return GetHostAndPortString(_HostUri.Host, _HostUri.Port, _HostHasPort);
1059  }
1060  return GetHostAndPortString(_Uri.Host, _Uri.Port, !_Uri.IsDefaultPort);
1061  }
1062  set
1063  {
1064  if (RequestSubmitted)
1065  {
1066  throw new InvalidOperationException(SR.GetString("net_writestarted"));
1067  }
1068  if (value == null)
1069  {
1070  throw new ArgumentNullException();
1071  }
1072  if (value.IndexOf('/') != -1 || !TryGetHostUri(value, out Uri hostUri))
1073  {
1074  throw new ArgumentException(SR.GetString("net_invalid_host"));
1075  }
1076  CheckConnectPermission(hostUri, needExecutionContext: false);
1077  _HostUri = hostUri;
1078  if (!_HostUri.IsDefaultPort)
1079  {
1080  _HostHasPort = true;
1081  return;
1082  }
1083  if (value.IndexOf(':') == -1)
1084  {
1085  _HostHasPort = false;
1086  return;
1087  }
1088  int num = value.IndexOf(']');
1089  if (num == -1)
1090  {
1091  _HostHasPort = true;
1092  }
1093  else
1094  {
1095  _HostHasPort = (value.LastIndexOf(':') > num);
1096  }
1097  }
1098  }
1099 
1100  internal bool UseCustomHost
1101  {
1102  get
1103  {
1104  if (_HostUri != null)
1105  {
1106  return !_RedirectedToDifferentHost;
1107  }
1108  return false;
1109  }
1110  }
1111 
1115  public int MaximumAutomaticRedirections
1116  {
1117  get
1118  {
1119  return _MaximumAllowedRedirections;
1120  }
1121  set
1122  {
1123  if (value <= 0)
1124  {
1125  throw new ArgumentException(SR.GetString("net_toosmall"), "value");
1126  }
1127  _MaximumAllowedRedirections = value;
1128  }
1129  }
1130 
1134  [global::__DynamicallyInvokable]
1135  public override string Method
1136  {
1137  [global::__DynamicallyInvokable]
1138  get
1139  {
1140  return _OriginVerb.Name;
1141  }
1142  [global::__DynamicallyInvokable]
1143  set
1144  {
1145  if (ValidationHelper.IsBlankString(value))
1146  {
1147  throw new ArgumentException(SR.GetString("net_badmethod"), "value");
1148  }
1149  if (ValidationHelper.IsInvalidHttpString(value))
1150  {
1151  throw new ArgumentException(SR.GetString("net_badmethod"), "value");
1152  }
1153  _OriginVerb = KnownHttpVerb.Parse(value);
1154  }
1155  }
1156 
1157  internal KnownHttpVerb CurrentMethod
1158  {
1159  get
1160  {
1161  if (_Verb == null)
1162  {
1163  return _OriginVerb;
1164  }
1165  return _Verb;
1166  }
1167  set
1168  {
1169  _Verb = value;
1170  }
1171  }
1172 
1175  [global::__DynamicallyInvokable]
1176  public override ICredentials Credentials
1177  {
1178  [global::__DynamicallyInvokable]
1179  get
1180  {
1181  return _AuthInfo;
1182  }
1183  [global::__DynamicallyInvokable]
1184  set
1185  {
1186  _AuthInfo = value;
1187  }
1188  }
1189 
1194  [global::__DynamicallyInvokable]
1195  public override bool UseDefaultCredentials
1196  {
1197  [global::__DynamicallyInvokable]
1198  get
1199  {
1200  if (!(Credentials is SystemNetworkCredential))
1201  {
1202  return false;
1203  }
1204  return true;
1205  }
1206  [global::__DynamicallyInvokable]
1207  set
1208  {
1209  if (RequestSubmitted)
1210  {
1211  throw new InvalidOperationException(SR.GetString("net_writestarted"));
1212  }
1213  _AuthInfo = (value ? CredentialCache.DefaultCredentials : null);
1214  }
1215  }
1216 
1217  internal bool IsTunnelRequest
1218  {
1219  get
1220  {
1221  return (_Booleans & Booleans.IsTunnelRequest) != (Booleans)0u;
1222  }
1223  set
1224  {
1225  if (value)
1226  {
1227  _Booleans |= Booleans.IsTunnelRequest;
1228  }
1229  else
1230  {
1231  _Booleans &= ~Booleans.IsTunnelRequest;
1232  }
1233  }
1234  }
1235 
1236  internal bool IsWebSocketRequest
1237  {
1238  get
1239  {
1240  return (_Booleans & Booleans.IsWebSocketRequest) != (Booleans)0u;
1241  }
1242  private set
1243  {
1244  if (value)
1245  {
1246  _Booleans |= Booleans.IsWebSocketRequest;
1247  }
1248  else
1249  {
1250  _Booleans &= ~Booleans.IsWebSocketRequest;
1251  }
1252  }
1253  }
1254 
1257  public override string ConnectionGroupName
1258  {
1259  get
1260  {
1261  return _ConnectionGroupName;
1262  }
1263  set
1264  {
1265  if (!IsWebSocketRequest)
1266  {
1267  _ConnectionGroupName = value;
1268  }
1269  }
1270  }
1271 
1272  internal bool InternalConnectionGroup
1273  {
1274  set
1275  {
1276  m_InternalConnectionGroup = value;
1277  }
1278  }
1279 
1283  [global::__DynamicallyInvokable]
1284  public override WebHeaderCollection Headers
1285  {
1286  [global::__DynamicallyInvokable]
1287  get
1288  {
1289  return _HttpRequestHeaders;
1290  }
1291  [global::__DynamicallyInvokable]
1292  set
1293  {
1294  if (RequestSubmitted)
1295  {
1296  throw new InvalidOperationException(SR.GetString("net_reqsubmitted"));
1297  }
1298  WebHeaderCollection webHeaderCollection = new WebHeaderCollection(WebHeaderCollectionType.HttpWebRequest);
1299  string[] allKeys = value.AllKeys;
1300  foreach (string name in allKeys)
1301  {
1302  webHeaderCollection.Add(name, value[name]);
1303  }
1304  _HttpRequestHeaders = webHeaderCollection;
1305  }
1306  }
1307 
1314  public override IWebProxy Proxy
1315  {
1316  get
1317  {
1318  ExceptionHelper.WebPermissionUnrestricted.Demand();
1319  return _Proxy;
1320  }
1321  set
1322  {
1323  ExceptionHelper.WebPermissionUnrestricted.Demand();
1324  if (RequestSubmitted)
1325  {
1326  throw new InvalidOperationException(SR.GetString("net_reqsubmitted"));
1327  }
1328  InternalProxy = value;
1329  }
1330  }
1331 
1332  internal IWebProxy InternalProxy
1333  {
1334  get
1335  {
1336  return _Proxy;
1337  }
1338  set
1339  {
1340  ProxySet = true;
1341  _Proxy = value;
1342  if (_ProxyChain != null)
1343  {
1344  _ProxyChain.Dispose();
1345  }
1346  _ProxyChain = null;
1347  ServicePoint servicePoint = FindServicePoint(forceFind: true);
1348  }
1349  }
1350 
1354  public Version ProtocolVersion
1355  {
1356  get
1357  {
1358  if (!IsVersionHttp10)
1359  {
1360  return HttpVersion.Version11;
1361  }
1362  return HttpVersion.Version10;
1363  }
1364  set
1365  {
1366  if (value.Equals(HttpVersion.Version11))
1367  {
1368  IsVersionHttp10 = false;
1369  return;
1370  }
1371  if (value.Equals(HttpVersion.Version10))
1372  {
1373  IsVersionHttp10 = true;
1374  return;
1375  }
1376  throw new ArgumentException(SR.GetString("net_wrongversion"), "value");
1377  }
1378  }
1379 
1382  [global::__DynamicallyInvokable]
1383  public override string ContentType
1384  {
1385  [global::__DynamicallyInvokable]
1386  get
1387  {
1388  return _HttpRequestHeaders["Content-Type"];
1389  }
1390  [global::__DynamicallyInvokable]
1391  set
1392  {
1393  SetSpecialHeaders("Content-Type", value);
1394  }
1395  }
1396 
1399  public string MediaType
1400  {
1401  get
1402  {
1403  return _MediaType;
1404  }
1405  set
1406  {
1407  _MediaType = value;
1408  }
1409  }
1410 
1417  public string TransferEncoding
1418  {
1419  get
1420  {
1421  return _HttpRequestHeaders["Transfer-Encoding"];
1422  }
1423  set
1424  {
1425  if (ValidationHelper.IsBlankString(value))
1426  {
1427  _HttpRequestHeaders.RemoveInternal("Transfer-Encoding");
1428  return;
1429  }
1430  string text = value.ToLower(CultureInfo.InvariantCulture);
1431  if (text.IndexOf("chunked") != -1)
1432  {
1433  throw new ArgumentException(SR.GetString("net_nochunked"), "value");
1434  }
1435  if (!SendChunked)
1436  {
1437  throw new InvalidOperationException(SR.GetString("net_needchunked"));
1438  }
1439  _HttpRequestHeaders.CheckUpdate("Transfer-Encoding", value);
1440  }
1441  }
1442 
1446  public string Connection
1447  {
1448  get
1449  {
1450  return _HttpRequestHeaders["Connection"];
1451  }
1452  set
1453  {
1454  if (ValidationHelper.IsBlankString(value))
1455  {
1456  _HttpRequestHeaders.RemoveInternal("Connection");
1457  return;
1458  }
1459  string text = value.ToLower(CultureInfo.InvariantCulture);
1460  bool flag = text.IndexOf("keep-alive") != -1;
1461  bool flag2 = text.IndexOf("close") != -1;
1462  if (flag | flag2)
1463  {
1464  throw new ArgumentException(SR.GetString("net_connarg"), "value");
1465  }
1466  _HttpRequestHeaders.CheckUpdate("Connection", value);
1467  }
1468  }
1469 
1472  [global::__DynamicallyInvokable]
1473  public string Accept
1474  {
1475  [global::__DynamicallyInvokable]
1476  get
1477  {
1478  return _HttpRequestHeaders["Accept"];
1479  }
1480  [global::__DynamicallyInvokable]
1481  set
1482  {
1483  SetSpecialHeaders("Accept", value);
1484  }
1485  }
1486 
1489  public string Referer
1490  {
1491  get
1492  {
1493  return _HttpRequestHeaders["Referer"];
1494  }
1495  set
1496  {
1497  SetSpecialHeaders("Referer", value);
1498  }
1499  }
1500 
1503  public string UserAgent
1504  {
1505  get
1506  {
1507  return _HttpRequestHeaders["User-Agent"];
1508  }
1509  set
1510  {
1511  SetSpecialHeaders("User-Agent", value);
1512  }
1513  }
1514 
1519  public string Expect
1520  {
1521  get
1522  {
1523  return _HttpRequestHeaders["Expect"];
1524  }
1525  set
1526  {
1527  if (ValidationHelper.IsBlankString(value))
1528  {
1529  _HttpRequestHeaders.RemoveInternal("Expect");
1530  return;
1531  }
1532  string text = value.ToLower(CultureInfo.InvariantCulture);
1533  if (text.IndexOf("100-continue") != -1)
1534  {
1535  throw new ArgumentException(SR.GetString("net_no100"), "value");
1536  }
1537  _HttpRequestHeaders.CheckUpdate("Expect", value);
1538  }
1539  }
1540 
1543  public DateTime IfModifiedSince
1544  {
1545  get
1546  {
1547  return GetDateHeaderHelper("If-Modified-Since");
1548  }
1549  set
1550  {
1551  SetDateHeaderHelper("If-Modified-Since", value);
1552  }
1553  }
1554 
1557  public DateTime Date
1558  {
1559  get
1560  {
1561  return GetDateHeaderHelper("Date");
1562  }
1563  set
1564  {
1565  SetDateHeaderHelper("Date", value);
1566  }
1567  }
1568 
1569  internal byte[] WriteBuffer => _WriteBuffer;
1570 
1571  internal int WriteBufferLength => _WriteBufferLength;
1572 
1573  internal int RequestContinueCount => _RequestContinueCount;
1574 
1575  private bool IdentityRequired
1576  {
1577  get
1578  {
1579  if (Credentials != null)
1580  {
1581  if (!(Credentials is SystemNetworkCredential))
1582  {
1583  if (!(Credentials is NetworkCredential))
1584  {
1585  CredentialCache credentialCache;
1586  if ((credentialCache = (Credentials as CredentialCache)) != null)
1587  {
1588  return credentialCache.IsDefaultInCache;
1589  }
1590  return true;
1591  }
1592  return false;
1593  }
1594  return true;
1595  }
1596  return false;
1597  }
1598  }
1599 
1600  internal ServerCertValidationCallback ServerCertValidationCallback
1601  {
1602  get;
1603  private set;
1604  }
1605 
1609  {
1610  get
1611  {
1612  if (ServerCertValidationCallback == null)
1613  {
1614  return null;
1615  }
1616  return ServerCertValidationCallback.ValidationCallback;
1617  }
1618  set
1619  {
1620  ExceptionHelper.InfrastructurePermission.Demand();
1621  if (value == null)
1622  {
1623  ServerCertValidationCallback = null;
1624  }
1625  else
1626  {
1627  ServerCertValidationCallback = new ServerCertValidationCallback(value);
1628  }
1629  }
1630  }
1631 
1632  private static string UniqueGroupId => Interlocked.Increment(ref s_UniqueGroupId).ToString(NumberFormatInfo.InvariantInfo);
1633 
1634  private bool SetRequestSubmitted()
1635  {
1636  bool requestSubmitted = RequestSubmitted;
1637  m_RequestSubmitted = true;
1638  return requestSubmitted;
1639  }
1640 
1641  internal string AuthHeader(HttpResponseHeader header)
1642  {
1643  if (_HttpResponse == null)
1644  {
1645  return null;
1646  }
1647  return _HttpResponse.Headers[header];
1648  }
1649 
1650  internal long SwitchToContentLength()
1651  {
1652  if (HaveResponse)
1653  {
1654  return -1L;
1655  }
1656  if (HttpWriteMode == HttpWriteMode.Chunked)
1657  {
1658  ConnectStream connectStream = _OldSubmitWriteStream;
1659  if (connectStream == null)
1660  {
1661  connectStream = _SubmitWriteStream;
1662  }
1663  if (connectStream.Connection != null && connectStream.Connection.IISVersion >= 6)
1664  {
1665  return -1L;
1666  }
1667  }
1668  long result = -1L;
1669  long contentLength = _ContentLength;
1670  if (HttpWriteMode != HttpWriteMode.None)
1671  {
1672  if (HttpWriteMode == HttpWriteMode.Buffer)
1673  {
1674  _ContentLength = _SubmitWriteStream.BufferedData.Length;
1675  m_OriginallyBuffered = true;
1676  HttpWriteMode = HttpWriteMode.ContentLength;
1677  return -1L;
1678  }
1679  if (NtlmKeepAlive && _OldSubmitWriteStream == null)
1680  {
1681  _ContentLength = 0L;
1682  _SubmitWriteStream.SuppressWrite = true;
1683  if (!_SubmitWriteStream.BufferOnly)
1684  {
1685  result = contentLength;
1686  }
1687  if (HttpWriteMode == HttpWriteMode.Chunked)
1688  {
1689  HttpWriteMode = HttpWriteMode.ContentLength;
1690  _SubmitWriteStream.SwitchToContentLength();
1691  result = -2L;
1692  _HttpRequestHeaders.RemoveInternal("Transfer-Encoding");
1693  }
1694  }
1695  if (_OldSubmitWriteStream != null)
1696  {
1697  if (NtlmKeepAlive)
1698  {
1699  _ContentLength = 0L;
1700  }
1701  else if (_ContentLength == 0L || HttpWriteMode == HttpWriteMode.Chunked)
1702  {
1703  if (_resendRequestContent == null)
1704  {
1705  if (_OldSubmitWriteStream.BufferedData != null)
1706  {
1707  _ContentLength = _OldSubmitWriteStream.BufferedData.Length;
1708  }
1709  }
1710  else if (HttpWriteMode == HttpWriteMode.Chunked)
1711  {
1712  _ContentLength = -1L;
1713  }
1714  else
1715  {
1716  _ContentLength = _originalContentLength;
1717  }
1718  }
1719  if (HttpWriteMode == HttpWriteMode.Chunked && (_resendRequestContent == null || NtlmKeepAlive))
1720  {
1721  HttpWriteMode = HttpWriteMode.ContentLength;
1722  _SubmitWriteStream.SwitchToContentLength();
1723  _HttpRequestHeaders.RemoveInternal("Transfer-Encoding");
1724  if (_resendRequestContent != null)
1725  {
1726  result = -2L;
1727  }
1728  }
1729  }
1730  }
1731  return result;
1732  }
1733 
1734  private void PostSwitchToContentLength(long value)
1735  {
1736  if (value > -1)
1737  {
1738  _ContentLength = value;
1739  }
1740  if (value == -2)
1741  {
1742  _ContentLength = -1L;
1743  HttpWriteMode = HttpWriteMode.Chunked;
1744  }
1745  }
1746 
1747  private void ClearAuthenticatedConnectionResources()
1748  {
1749  if (ProxyAuthenticationState.UniqueGroupId != null || ServerAuthenticationState.UniqueGroupId != null)
1750  {
1751  ServicePoint.ReleaseConnectionGroup(GetConnectionGroupLine());
1752  }
1753  UnlockConnectionDelegate unlockConnectionDelegate = UnlockConnectionDelegate;
1754  try
1755  {
1756  unlockConnectionDelegate?.Invoke();
1757  UnlockConnectionDelegate = null;
1758  }
1759  catch (Exception exception)
1760  {
1761  if (NclUtilities.IsFatal(exception))
1762  {
1763  throw;
1764  }
1765  }
1766  ProxyAuthenticationState.ClearSession(this);
1767  ServerAuthenticationState.ClearSession(this);
1768  }
1769 
1770  private void CheckProtocol(bool onRequestStream)
1771  {
1772  if (!CanGetRequestStream)
1773  {
1774  if (onRequestStream)
1775  {
1776  throw new ProtocolViolationException(SR.GetString("net_nouploadonget"));
1777  }
1778  if ((HttpWriteMode != 0 && HttpWriteMode != HttpWriteMode.None) || ContentLength > 0 || SendChunked)
1779  {
1780  throw new ProtocolViolationException(SR.GetString("net_nocontentlengthonget"));
1781  }
1782  HttpWriteMode = HttpWriteMode.None;
1783  }
1784  else if (HttpWriteMode == HttpWriteMode.Unknown)
1785  {
1786  if (SendChunked)
1787  {
1788  if (ServicePoint.HttpBehaviour == HttpBehaviour.HTTP11 || ServicePoint.HttpBehaviour == HttpBehaviour.Unknown)
1789  {
1790  HttpWriteMode = HttpWriteMode.Chunked;
1791  }
1792  else
1793  {
1795  {
1796  throw new ProtocolViolationException(SR.GetString("net_nochunkuploadonhttp10"));
1797  }
1798  HttpWriteMode = HttpWriteMode.Buffer;
1799  }
1800  }
1801  else
1802  {
1803  HttpWriteMode = ((ContentLength >= 0) ? HttpWriteMode.ContentLength : (onRequestStream ? HttpWriteMode.Buffer : HttpWriteMode.None));
1804  }
1805  }
1806  if (HttpWriteMode != HttpWriteMode.Chunked)
1807  {
1808  if ((onRequestStream || _OriginVerb.Equals(KnownHttpVerb.Post) || _OriginVerb.Equals(KnownHttpVerb.Put)) && ContentLength == -1 && !AllowWriteStreamBuffering && KeepAlive)
1809  {
1810  throw new ProtocolViolationException(SR.GetString("net_contentlengthmissing"));
1811  }
1812  if (!ValidationHelper.IsBlankString(TransferEncoding))
1813  {
1814  throw new InvalidOperationException(SR.GetString("net_needchunked"));
1815  }
1816  }
1817  }
1818 
1831  [global::__DynamicallyInvokable]
1832  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
1833  public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
1834  {
1835  bool success = false;
1836  try
1837  {
1838  if (Logging.On)
1839  {
1840  Logging.Enter(Logging.Web, this, "BeginGetRequestStream", "");
1841  }
1842  CheckProtocol(onRequestStream: true);
1843  ContextAwareResult contextAwareResult = new ContextAwareResult(IdentityRequired, forceCaptureContext: true, this, state, callback);
1844  lock (contextAwareResult.StartPostingAsyncOp())
1845  {
1846  if (_WriteAResult != null && _WriteAResult.InternalPeekCompleted)
1847  {
1848  if (_WriteAResult.Result is Exception)
1849  {
1850  throw (Exception)_WriteAResult.Result;
1851  }
1852  try
1853  {
1854  contextAwareResult.InvokeCallback(_WriteAResult.Result);
1855  }
1856  catch (Exception exception)
1857  {
1858  Abort(exception, 1);
1859  throw;
1860  }
1861  }
1862  else
1863  {
1864  if (!RequestSubmitted && NclUtilities.IsThreadPoolLow())
1865  {
1866  Exception ex = new InvalidOperationException(SR.GetString("net_needmorethreads"));
1867  Abort(ex, 1);
1868  throw ex;
1869  }
1870  lock (this)
1871  {
1872  if (_WriteAResult != null)
1873  {
1874  throw new InvalidOperationException(SR.GetString("net_repcall"));
1875  }
1876  if (SetRequestSubmitted())
1877  {
1878  throw new InvalidOperationException(SR.GetString("net_reqsubmitted"));
1879  }
1880  if (_ReadAResult != null)
1881  {
1882  throw (Exception)_ReadAResult.Result;
1883  }
1884  _WriteAResult = contextAwareResult;
1885  Async = true;
1886  }
1887  CurrentMethod = _OriginVerb;
1888  BeginSubmitRequest();
1889  }
1890  contextAwareResult.FinishPostingAsyncOp();
1891  }
1892  if (Logging.On)
1893  {
1894  Logging.Exit(Logging.Web, this, "BeginGetRequestStream", contextAwareResult);
1895  }
1896  success = true;
1897  return contextAwareResult;
1898  }
1899  finally
1900  {
1901  if (FrameworkEventSource.Log.IsEnabled())
1902  {
1903  LogBeginGetRequestStream(success, synchronous: false);
1904  }
1905  }
1906  }
1907 
1919  [global::__DynamicallyInvokable]
1920  public override Stream EndGetRequestStream(IAsyncResult asyncResult)
1921  {
1922  TransportContext context;
1923  return EndGetRequestStream(asyncResult, out context);
1924  }
1925 
1938  public Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context)
1939  {
1940  bool success = false;
1941  try
1942  {
1943  if (Logging.On)
1944  {
1945  Logging.Enter(Logging.Web, this, "EndGetRequestStream", "");
1946  }
1947  context = null;
1948  if (asyncResult == null)
1949  {
1950  throw new ArgumentNullException("asyncResult");
1951  }
1952  LazyAsyncResult lazyAsyncResult = asyncResult as LazyAsyncResult;
1953  if (lazyAsyncResult == null || lazyAsyncResult.AsyncObject != this)
1954  {
1955  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
1956  }
1957  if (lazyAsyncResult.EndCalled)
1958  {
1959  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndGetRequestStream"));
1960  }
1961  ConnectStream connectStream = lazyAsyncResult.InternalWaitForCompletion() as ConnectStream;
1962  lazyAsyncResult.EndCalled = true;
1963  if (connectStream == null)
1964  {
1965  if (Logging.On)
1966  {
1967  Logging.Exception(Logging.Web, this, "EndGetRequestStream", lazyAsyncResult.Result as Exception);
1968  }
1969  throw (Exception)lazyAsyncResult.Result;
1970  }
1971  context = new ConnectStreamContext(connectStream);
1972  if (Logging.On)
1973  {
1974  Logging.Exit(Logging.Web, this, "EndGetRequestStream", connectStream);
1975  }
1976  success = true;
1977  return connectStream;
1978  }
1979  finally
1980  {
1981  if (FrameworkEventSource.Log.IsEnabled())
1982  {
1983  LogEndGetRequestStream(success, synchronous: false);
1984  }
1985  }
1986  }
1987 
1998  public override Stream GetRequestStream()
1999  {
2000  TransportContext context;
2001  return GetRequestStream(out context);
2002  }
2003 
2016  {
2017  bool success = false;
2018  try
2019  {
2020  if (FrameworkEventSource.Log.IsEnabled())
2021  {
2022  LogBeginGetRequestStream(success: true, synchronous: true);
2023  }
2024  if (Logging.On)
2025  {
2026  Logging.Enter(Logging.Web, this, "GetRequestStream", "");
2027  }
2028  context = null;
2029  CheckProtocol(onRequestStream: true);
2030  if (_WriteAResult == null || !_WriteAResult.InternalPeekCompleted)
2031  {
2032  lock (this)
2033  {
2034  if (_WriteAResult != null)
2035  {
2036  throw new InvalidOperationException(SR.GetString("net_repcall"));
2037  }
2038  if (SetRequestSubmitted())
2039  {
2040  throw new InvalidOperationException(SR.GetString("net_reqsubmitted"));
2041  }
2042  if (_ReadAResult != null)
2043  {
2044  throw (Exception)_ReadAResult.Result;
2045  }
2046  _WriteAResult = new LazyAsyncResult(this, null, null);
2047  Async = false;
2048  }
2049  CurrentMethod = _OriginVerb;
2050  while (m_Retry && !_WriteAResult.InternalPeekCompleted)
2051  {
2052  _OldSubmitWriteStream = null;
2053  _SubmitWriteStream = null;
2054  BeginSubmitRequest();
2055  }
2056  while (Aborted && !_WriteAResult.InternalPeekCompleted)
2057  {
2058  if (!(_CoreResponse is Exception))
2059  {
2060  Thread.SpinWait(1);
2061  }
2062  else
2063  {
2064  CheckWriteSideResponseProcessing();
2065  }
2066  }
2067  }
2068  ConnectStream connectStream = _WriteAResult.InternalWaitForCompletion() as ConnectStream;
2069  _WriteAResult.EndCalled = true;
2070  success = true;
2071  if (connectStream == null)
2072  {
2073  if (Logging.On)
2074  {
2075  Logging.Exception(Logging.Web, this, "EndGetRequestStream", _WriteAResult.Result as Exception);
2076  }
2077  throw (Exception)_WriteAResult.Result;
2078  }
2079  context = new ConnectStreamContext(connectStream);
2080  if (Logging.On)
2081  {
2082  Logging.Exit(Logging.Web, this, "GetRequestStream", connectStream);
2083  }
2084  return connectStream;
2085  }
2086  finally
2087  {
2088  if (FrameworkEventSource.Log.IsEnabled())
2089  {
2090  LogEndGetRequestStream(success, synchronous: true);
2091  }
2092  }
2093  }
2094 
2095  internal void ErrorStatusCodeNotify(Connection connection, bool isKeepAlive, bool fatal)
2096  {
2097  ConnectStream submitWriteStream = _SubmitWriteStream;
2098  if (submitWriteStream != null && submitWriteStream.Connection == connection)
2099  {
2100  if (!fatal)
2101  {
2102  submitWriteStream.ErrorResponseNotify(isKeepAlive);
2103  }
2104  else if (!Aborted)
2105  {
2106  submitWriteStream.FatalResponseNotify();
2107  }
2108  }
2109  }
2110 
2111  private HttpProcessingResult DoSubmitRequestProcessing(ref Exception exception)
2112  {
2113  HttpProcessingResult httpProcessingResult = HttpProcessingResult.Continue;
2114  m_Retry = false;
2115  bool ntlmKeepAlive = NtlmKeepAlive;
2116  try
2117  {
2118  if (_HttpResponse != null)
2119  {
2120  if (_CookieContainer != null)
2121  {
2122  CookieModule.OnReceivedHeaders(this);
2123  }
2124  ProxyAuthenticationState.Update(this);
2125  ServerAuthenticationState.Update(this);
2126  }
2127  bool flag = false;
2128  bool flag2 = true;
2129  bool disableUpload = false;
2130  if (_HttpResponse == null)
2131  {
2132  flag = true;
2133  }
2134  else if (CheckResubmitForCache(ref exception) || CheckResubmit(ref exception, ref disableUpload))
2135  {
2136  flag = true;
2137  flag2 = false;
2138  }
2139  else if (disableUpload)
2140  {
2141  flag = false;
2142  flag2 = false;
2143  httpProcessingResult = HttpProcessingResult.WriteWait;
2144  _AutoRedirects--;
2145  OpenWriteSideResponseWindow();
2146  ConnectionReturnResult returnResult = new ConnectionReturnResult(1);
2147  ConnectionReturnResult.Add(ref returnResult, this, _HttpResponse.CoreResponseData);
2148  m_PendingReturnResult = returnResult;
2149  _HttpResponse = null;
2150  _SubmitWriteStream.FinishedAfterWrite = true;
2151  SetRequestContinue();
2152  }
2153  ServicePoint servicePoint = null;
2154  if (flag2)
2155  {
2156  WebException ex = exception as WebException;
2157  if (ex != null && ex.InternalStatus == WebExceptionInternalStatus.ServicePointFatal)
2158  {
2159  ProxyChain proxyChain = _ProxyChain;
2160  if (proxyChain != null)
2161  {
2162  servicePoint = ServicePointManager.FindServicePoint(proxyChain);
2163  }
2164  flag = (servicePoint != null);
2165  }
2166  }
2167  if (!flag)
2168  {
2169  return httpProcessingResult;
2170  }
2171  if (base.CacheProtocol != null && _HttpResponse != null)
2172  {
2173  base.CacheProtocol.Reset();
2174  }
2175  ClearRequestForResubmit(ntlmKeepAlive);
2176  WebException ex2 = exception as WebException;
2177  if (ex2 != null && (ex2.Status == WebExceptionStatus.PipelineFailure || ex2.Status == WebExceptionStatus.KeepAliveFailure))
2178  {
2179  m_Extra401Retry = true;
2180  }
2181  if (servicePoint == null)
2182  {
2183  servicePoint = FindServicePoint(forceFind: true);
2184  }
2185  else
2186  {
2187  _ServicePoint = servicePoint;
2188  }
2189  if (Async)
2190  {
2191  SubmitRequest(servicePoint);
2192  }
2193  else
2194  {
2195  m_Retry = true;
2196  }
2197  httpProcessingResult = HttpProcessingResult.WriteWait;
2198  return httpProcessingResult;
2199  }
2200  finally
2201  {
2202  if (httpProcessingResult == HttpProcessingResult.Continue)
2203  {
2204  ClearAuthenticatedConnectionResources();
2205  }
2206  }
2207  }
2208 
2220  [global::__DynamicallyInvokable]
2221  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2222  public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
2223  {
2224  bool success = false;
2225  try
2226  {
2227  if (Logging.On)
2228  {
2229  Logging.Enter(Logging.Web, this, "BeginGetResponse", "");
2230  }
2231  if (!RequestSubmitted)
2232  {
2233  CheckProtocol(onRequestStream: false);
2234  }
2235  ConnectStream connectStream = (_OldSubmitWriteStream != null) ? _OldSubmitWriteStream : _SubmitWriteStream;
2236  if (connectStream != null && !connectStream.IsClosed)
2237  {
2238  if (connectStream.BytesLeftToWrite > 0)
2239  {
2240  throw new ProtocolViolationException(SR.GetString("net_entire_body_not_written"));
2241  }
2242  connectStream.Close();
2243  }
2244  else if (connectStream == null && HasEntityBody)
2245  {
2246  throw new ProtocolViolationException(SR.GetString("net_must_provide_request_body"));
2247  }
2248  ContextAwareResult contextAwareResult = new ContextAwareResult(IdentityRequired, forceCaptureContext: true, this, state, callback);
2249  if (!RequestSubmitted && NclUtilities.IsThreadPoolLow())
2250  {
2251  Exception ex = new InvalidOperationException(SR.GetString("net_needmorethreads"));
2252  Abort(ex, 1);
2253  throw ex;
2254  }
2255  lock (contextAwareResult.StartPostingAsyncOp())
2256  {
2257  bool flag = false;
2258  bool flag2;
2259  lock (this)
2260  {
2261  flag2 = SetRequestSubmitted();
2262  if (HaveResponse)
2263  {
2264  flag = true;
2265  }
2266  else
2267  {
2268  if (_ReadAResult != null)
2269  {
2270  throw new InvalidOperationException(SR.GetString("net_repcall"));
2271  }
2272  _ReadAResult = contextAwareResult;
2273  Async = true;
2274  }
2275  }
2276  CheckDeferredCallDone(connectStream);
2277  if (flag)
2278  {
2279  if (Logging.On)
2280  {
2281  Logging.Exit(Logging.Web, this, "BeginGetResponse", _ReadAResult.Result);
2282  }
2283  Exception ex2 = _ReadAResult.Result as Exception;
2284  if (ex2 != null)
2285  {
2286  throw ex2;
2287  }
2288  try
2289  {
2290  contextAwareResult.InvokeCallback(_ReadAResult.Result);
2291  }
2292  catch (Exception exception)
2293  {
2294  Abort(exception, 1);
2295  throw;
2296  }
2297  }
2298  else
2299  {
2300  if (!flag2)
2301  {
2302  CurrentMethod = _OriginVerb;
2303  }
2304  if (_RerequestCount > 0 || !flag2)
2305  {
2306  while (m_Retry)
2307  {
2308  BeginSubmitRequest();
2309  }
2310  }
2311  }
2312  contextAwareResult.FinishPostingAsyncOp();
2313  }
2314  if (Logging.On)
2315  {
2316  Logging.Exit(Logging.Web, this, "BeginGetResponse", contextAwareResult);
2317  }
2318  success = true;
2319  return contextAwareResult;
2320  }
2321  finally
2322  {
2323  if (FrameworkEventSource.Log.IsEnabled())
2324  {
2325  LogBeginGetResponse(success, synchronous: false);
2326  }
2327  }
2328  }
2329 
2340  [global::__DynamicallyInvokable]
2341  public override WebResponse EndGetResponse(IAsyncResult asyncResult)
2342  {
2343  bool success = false;
2344  int statusCode = -1;
2345  try
2346  {
2347  if (Logging.On)
2348  {
2349  Logging.Enter(Logging.Web, this, "EndGetResponse", "");
2350  }
2351  if (asyncResult == null)
2352  {
2353  throw new ArgumentNullException("asyncResult");
2354  }
2355  LazyAsyncResult lazyAsyncResult = asyncResult as LazyAsyncResult;
2356  if (lazyAsyncResult == null || lazyAsyncResult.AsyncObject != this)
2357  {
2358  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
2359  }
2360  if (lazyAsyncResult.EndCalled)
2361  {
2362  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndGetResponse"));
2363  }
2364  HttpWebResponse httpWebResponse = lazyAsyncResult.InternalWaitForCompletion() as HttpWebResponse;
2365  lazyAsyncResult.EndCalled = true;
2366  if (httpWebResponse == null)
2367  {
2368  if (Logging.On)
2369  {
2370  Logging.Exception(Logging.Web, this, "EndGetResponse", lazyAsyncResult.Result as Exception);
2371  }
2372  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.HttpWebRequestFailed);
2373  throw (Exception)lazyAsyncResult.Result;
2374  }
2375  if (Logging.On)
2376  {
2377  Logging.Exit(Logging.Web, this, "EndGetResponse", httpWebResponse);
2378  }
2379  InitLifetimeTracking(httpWebResponse);
2380  statusCode = GetStatusCode(httpWebResponse);
2381  success = true;
2382  return httpWebResponse;
2383  }
2384  catch (WebException ex)
2385  {
2386  HttpWebResponse httpWebResponse2 = ex.Response as HttpWebResponse;
2387  statusCode = GetStatusCode(httpWebResponse2);
2388  throw;
2389  }
2390  finally
2391  {
2392  if (FrameworkEventSource.Log.IsEnabled())
2393  {
2394  LogEndGetResponse(success, synchronous: false, statusCode);
2395  }
2396  }
2397  }
2398 
2399  private void CheckDeferredCallDone(ConnectStream stream)
2400  {
2401  object obj = Interlocked.Exchange(ref m_PendingReturnResult, DBNull.Value);
2402  if (obj == NclConstants.Sentinel)
2403  {
2404  EndSubmitRequest();
2405  }
2406  else if (obj != null && obj != DBNull.Value)
2407  {
2408  stream.ProcessWriteCallDone(obj as ConnectionReturnResult);
2409  }
2410  }
2411 
2422  public override WebResponse GetResponse()
2423  {
2424  bool success = false;
2425  int statusCode = -1;
2426  try
2427  {
2428  if (FrameworkEventSource.Log.IsEnabled())
2429  {
2430  LogBeginGetResponse(success: true, synchronous: true);
2431  }
2432  if (Logging.On)
2433  {
2434  Logging.Enter(Logging.Web, this, "GetResponse", "");
2435  }
2436  if (!RequestSubmitted)
2437  {
2438  CheckProtocol(onRequestStream: false);
2439  }
2440  ConnectStream connectStream = (_OldSubmitWriteStream != null) ? _OldSubmitWriteStream : _SubmitWriteStream;
2441  if (connectStream != null && !connectStream.IsClosed)
2442  {
2443  if (connectStream.BytesLeftToWrite > 0)
2444  {
2445  throw new ProtocolViolationException(SR.GetString("net_entire_body_not_written"));
2446  }
2447  connectStream.Close();
2448  }
2449  else if (connectStream == null && HasEntityBody)
2450  {
2451  throw new ProtocolViolationException(SR.GetString("net_must_provide_request_body"));
2452  }
2453  bool flag = false;
2454  HttpWebResponse httpWebResponse = null;
2455  bool flag2;
2456  lock (this)
2457  {
2458  flag2 = SetRequestSubmitted();
2459  if (HaveResponse)
2460  {
2461  flag = true;
2462  httpWebResponse = (_ReadAResult.Result as HttpWebResponse);
2463  }
2464  else
2465  {
2466  if (_ReadAResult != null)
2467  {
2468  throw new InvalidOperationException(SR.GetString("net_repcall"));
2469  }
2470  Async = false;
2471  if (Async)
2472  {
2473  ContextAwareResult contextAwareResult = new ContextAwareResult(IdentityRequired, forceCaptureContext: true, this, null, null);
2474  contextAwareResult.StartPostingAsyncOp(lockCapture: false);
2475  contextAwareResult.FinishPostingAsyncOp();
2476  _ReadAResult = contextAwareResult;
2477  }
2478  else
2479  {
2480  _ReadAResult = new LazyAsyncResult(this, null, null);
2481  }
2482  }
2483  }
2484  CheckDeferredCallDone(connectStream);
2485  if (!flag)
2486  {
2487  if (_Timer == null)
2488  {
2489  _Timer = TimerQueue.CreateTimer(s_TimeoutCallback, this);
2490  }
2491  if (!flag2)
2492  {
2493  CurrentMethod = _OriginVerb;
2494  }
2495  while (m_Retry)
2496  {
2497  BeginSubmitRequest();
2498  }
2499  while (!Async && Aborted && !_ReadAResult.InternalPeekCompleted)
2500  {
2501  if (!(_CoreResponse is Exception))
2502  {
2503  Thread.SpinWait(1);
2504  }
2505  else
2506  {
2507  CheckWriteSideResponseProcessing();
2508  }
2509  }
2510  httpWebResponse = (_ReadAResult.InternalWaitForCompletion() as HttpWebResponse);
2511  _ReadAResult.EndCalled = true;
2512  }
2513  if (httpWebResponse == null)
2514  {
2515  if (Logging.On)
2516  {
2517  Logging.Exception(Logging.Web, this, "GetResponse", _ReadAResult.Result as Exception);
2518  }
2519  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.HttpWebRequestFailed);
2520  throw (Exception)_ReadAResult.Result;
2521  }
2522  if (Logging.On)
2523  {
2524  Logging.Exit(Logging.Web, this, "GetResponse", httpWebResponse);
2525  }
2526  if (!flag)
2527  {
2528  InitLifetimeTracking(httpWebResponse);
2529  }
2530  statusCode = GetStatusCode(httpWebResponse);
2531  success = true;
2532  return httpWebResponse;
2533  }
2534  catch (WebException ex)
2535  {
2536  HttpWebResponse httpWebResponse2 = ex.Response as HttpWebResponse;
2537  statusCode = GetStatusCode(httpWebResponse2);
2538  throw;
2539  }
2540  finally
2541  {
2542  if (FrameworkEventSource.Log.IsEnabled())
2543  {
2544  LogEndGetResponse(success, synchronous: true, statusCode);
2545  }
2546  }
2547  }
2548 
2549  private void InitLifetimeTracking(HttpWebResponse httpWebResponse)
2550  {
2551  IRequestLifetimeTracker requestLifetimeTracker = httpWebResponse.ResponseStream as IRequestLifetimeTracker;
2552  requestLifetimeTracker.TrackRequestLifetime(m_StartTimestamp);
2553  }
2554 
2555  internal void WriteCallDone(ConnectStream stream, ConnectionReturnResult returnResult)
2556  {
2557  if (stream != ((_OldSubmitWriteStream != null) ? _OldSubmitWriteStream : _SubmitWriteStream))
2558  {
2559  stream.ProcessWriteCallDone(returnResult);
2560  return;
2561  }
2562  if (!UserRetrievedWriteStream)
2563  {
2564  stream.ProcessWriteCallDone(returnResult);
2565  return;
2566  }
2567  if (stream.FinishedAfterWrite)
2568  {
2569  stream.ProcessWriteCallDone(returnResult);
2570  return;
2571  }
2572  object value = (returnResult == null) ? ((object)Missing.Value) : ((object)returnResult);
2573  object obj = Interlocked.CompareExchange(ref m_PendingReturnResult, value, null);
2574  if (obj == DBNull.Value)
2575  {
2576  stream.ProcessWriteCallDone(returnResult);
2577  }
2578  }
2579 
2580  internal void NeedEndSubmitRequest()
2581  {
2582  object obj = Interlocked.CompareExchange(ref m_PendingReturnResult, NclConstants.Sentinel, null);
2583  if (obj == DBNull.Value)
2584  {
2585  EndSubmitRequest();
2586  }
2587  }
2588 
2589  internal void CallContinueDelegateCallback(object state)
2590  {
2591  CoreResponseData coreResponseData = (CoreResponseData)state;
2592  ContinueDelegate((int)coreResponseData.m_StatusCode, coreResponseData.m_ResponseHeaders);
2593  }
2594 
2595  private DateTime GetDateHeaderHelper(string headerName)
2596  {
2597  string text = _HttpRequestHeaders[headerName];
2598  if (text == null)
2599  {
2600  return DateTime.MinValue;
2601  }
2602  return HttpProtocolUtils.string2date(text);
2603  }
2604 
2605  private void SetDateHeaderHelper(string headerName, DateTime dateTime)
2606  {
2607  if (dateTime == DateTime.MinValue)
2608  {
2609  SetSpecialHeaders(headerName, null);
2610  }
2611  else
2612  {
2613  SetSpecialHeaders(headerName, HttpProtocolUtils.date2string(dateTime));
2614  }
2615  }
2616 
2617  internal void FreeWriteBuffer()
2618  {
2619  if (_WriteBufferFromPinnableCache)
2620  {
2621  _WriteBufferCache.FreeBuffer(_WriteBuffer);
2622  _WriteBufferFromPinnableCache = false;
2623  }
2624  _WriteBufferLength = 0;
2625  _WriteBuffer = null;
2626  }
2627 
2628  private void SetWriteBuffer(int bufferSize)
2629  {
2630  if (bufferSize <= 512)
2631  {
2632  if (!_WriteBufferFromPinnableCache)
2633  {
2634  _WriteBuffer = _WriteBufferCache.AllocateBuffer();
2635  _WriteBufferFromPinnableCache = true;
2636  }
2637  }
2638  else
2639  {
2640  FreeWriteBuffer();
2641  _WriteBuffer = new byte[bufferSize];
2642  }
2643  _WriteBufferLength = bufferSize;
2644  }
2645 
2646  private void SetSpecialHeaders(string HeaderName, string value)
2647  {
2648  value = WebHeaderCollection.CheckBadChars(value, isHeaderValue: true);
2649  _HttpRequestHeaders.RemoveInternal(HeaderName);
2650  if (value.Length != 0)
2651  {
2652  _HttpRequestHeaders.AddInternal(HeaderName, value);
2653  }
2654  }
2655 
2657  [global::__DynamicallyInvokable]
2658  public override void Abort()
2659  {
2660  Abort(null, 1);
2661  }
2662 
2663  private void Abort(Exception exception, int abortState)
2664  {
2665  if (Logging.On)
2666  {
2667  Logging.Enter(Logging.Web, this, "Abort", (exception == null) ? "" : exception.Message);
2668  }
2669  if (Interlocked.CompareExchange(ref m_Aborted, abortState, 0) == 0)
2670  {
2671  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.HttpWebRequestAborted);
2672  m_OnceFailed = true;
2673  CancelTimer();
2674  WebException ex = exception as WebException;
2675  if (exception == null)
2676  {
2677  ex = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
2678  }
2679  else if (ex == null)
2680  {
2681  ex = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), exception, WebExceptionStatus.RequestCanceled, _HttpResponse);
2682  }
2683  try
2684  {
2686  HttpAbortDelegate abortDelegate = _AbortDelegate;
2687  if (abortDelegate == null || abortDelegate(this, ex))
2688  {
2689  SetResponse(ex);
2690  }
2691  else
2692  {
2693  LazyAsyncResult lazyAsyncResult = null;
2694  LazyAsyncResult lazyAsyncResult2 = null;
2695  if (!Async)
2696  {
2697  lock (this)
2698  {
2699  lazyAsyncResult = _WriteAResult;
2700  lazyAsyncResult2 = _ReadAResult;
2701  }
2702  }
2703  lazyAsyncResult?.InvokeCallback(ex);
2704  lazyAsyncResult2?.InvokeCallback(ex);
2705  }
2706  if (!Async)
2707  {
2708  LazyAsyncResult connectionAsyncResult = ConnectionAsyncResult;
2709  LazyAsyncResult connectionReaderAsyncResult = ConnectionReaderAsyncResult;
2710  connectionAsyncResult?.InvokeCallback(ex);
2711  connectionReaderAsyncResult?.InvokeCallback(ex);
2712  }
2713  if (IsWebSocketRequest && ServicePoint != null)
2714  {
2716  }
2717  }
2718  catch (InternalException)
2719  {
2720  }
2721  }
2722  if (Logging.On)
2723  {
2724  Logging.Exit(Logging.Web, this, "Abort", "");
2725  }
2726  }
2727 
2728  private void CancelTimer()
2729  {
2730  _Timer?.Cancel();
2731  }
2732 
2733  private static void TimeoutCallback(TimerThread.Timer timer, int timeNoticed, object context)
2734  {
2735  ThreadPool.UnsafeQueueUserWorkItem(s_AbortWrapper, context);
2736  }
2737 
2738  private static void AbortWrapper(object context)
2739  {
2740  ((HttpWebRequest)context).Abort(new WebException(NetRes.GetWebStatusString(WebExceptionStatus.Timeout), WebExceptionStatus.Timeout), 1);
2741  }
2742 
2743  private ServicePoint FindServicePoint(bool forceFind)
2744  {
2745  ServicePoint servicePoint = _ServicePoint;
2746  if ((servicePoint == null) | forceFind)
2747  {
2748  lock (this)
2749  {
2750  if ((_ServicePoint == null) | forceFind)
2751  {
2752  if (!ProxySet)
2753  {
2754  _Proxy = WebRequest.InternalDefaultWebProxy;
2755  }
2756  if (_ProxyChain != null)
2757  {
2758  _ProxyChain.Dispose();
2759  }
2760  _ServicePoint = ServicePointManager.FindServicePoint(_Uri, _Proxy, out _ProxyChain, ref _AbortDelegate, ref m_Aborted);
2761  if (Logging.On)
2762  {
2763  Logging.Associate(Logging.Web, this, _ServicePoint);
2764  }
2765  }
2766  }
2767  servicePoint = _ServicePoint;
2768  }
2769  return servicePoint;
2770  }
2771 
2772  private void InvokeGetRequestStreamCallback()
2773  {
2774  LazyAsyncResult writeAResult = _WriteAResult;
2775  if (writeAResult != null)
2776  {
2777  try
2778  {
2779  writeAResult.InvokeCallback(_SubmitWriteStream);
2780  }
2781  catch (Exception exception)
2782  {
2783  if (NclUtilities.IsFatal(exception))
2784  {
2785  throw;
2786  }
2787  Abort(exception, 1);
2788  throw;
2789  }
2790  }
2791  }
2792 
2793  internal void SetRequestSubmitDone(ConnectStream submitStream)
2794  {
2795  if (!Async)
2796  {
2797  ConnectionAsyncResult.InvokeCallback();
2798  }
2800  {
2801  submitStream.EnableWriteBuffering();
2802  }
2803  if (submitStream.CanTimeout)
2804  {
2805  submitStream.ReadTimeout = ReadWriteTimeout;
2806  submitStream.WriteTimeout = ReadWriteTimeout;
2807  }
2808  if (Logging.On)
2809  {
2810  Logging.Associate(Logging.Web, this, submitStream);
2811  }
2812  TransportContext transportContext = new ConnectStreamContext(submitStream);
2813  ServerAuthenticationState.TransportContext = transportContext;
2814  ProxyAuthenticationState.TransportContext = transportContext;
2815  _SubmitWriteStream = submitStream;
2816  if (RtcState != null && RtcState.inputData != null && !RtcState.IsAborted)
2817  {
2818  RtcState.outputData = new byte[4];
2819  RtcState.result = _SubmitWriteStream.SetRtcOption(RtcState.inputData, RtcState.outputData);
2820  if (!RtcState.IsEnabled())
2821  {
2822  Abort(null, 1);
2823  }
2824  RtcState.connectComplete.Set();
2825  }
2826  if (Async && _CoreResponse != null && _CoreResponse != DBNull.Value)
2827  {
2828  submitStream.CallDone();
2829  }
2830  else
2831  {
2832  EndSubmitRequest();
2833  }
2834  }
2835 
2836  internal void WriteHeadersCallback(WebExceptionStatus errorStatus, ConnectStream stream, bool async)
2837  {
2838  if (errorStatus == WebExceptionStatus.Success)
2839  {
2840  if (!EndWriteHeaders(async))
2841  {
2842  errorStatus = WebExceptionStatus.Pending;
2843  }
2844  else if (stream.BytesLeftToWrite == 0L)
2845  {
2846  stream.CallDone();
2847  }
2848  }
2849  }
2850 
2851  internal void SetRequestContinue()
2852  {
2853  SetRequestContinue(null);
2854  }
2855 
2856  internal void SetRequestContinue(CoreResponseData continueResponse)
2857  {
2858  _RequestContinueCount++;
2859  if (HttpWriteMode == HttpWriteMode.None || !m_ContinueGate.Complete())
2860  {
2861  return;
2862  }
2863  if (continueResponse != null && ContinueDelegate != null)
2864  {
2865  ExecutionContext executionContext = Async ? GetWritingContext().ContextCopy : null;
2866  if (executionContext == null)
2867  {
2868  ContinueDelegate((int)continueResponse.m_StatusCode, continueResponse.m_ResponseHeaders);
2869  }
2870  else
2871  {
2872  ExecutionContext.Run(executionContext, CallContinueDelegateCallback, continueResponse);
2873  }
2874  }
2875  EndWriteHeaders_Part2();
2876  }
2877 
2878  internal void OpenWriteSideResponseWindow()
2879  {
2880  _CoreResponse = DBNull.Value;
2881  _NestedWriteSideCheck = 0;
2882  }
2883 
2884  internal void CheckWriteSideResponseProcessing()
2885  {
2886  object obj = Async ? Interlocked.CompareExchange(ref _CoreResponse, null, DBNull.Value) : _CoreResponse;
2887  if (obj != DBNull.Value && obj != null && (Async || ++_NestedWriteSideCheck == 1))
2888  {
2889  FinishContinueWait();
2890  Exception ex = obj as Exception;
2891  if (ex != null)
2892  {
2893  SetResponse(ex);
2894  }
2895  else
2896  {
2897  SetResponse(obj as CoreResponseData);
2898  }
2899  }
2900  }
2901 
2902  internal void SetAndOrProcessResponse(object responseOrException)
2903  {
2904  if (responseOrException == null)
2905  {
2906  throw new InternalException();
2907  }
2908  CoreResponseData coreResponseData = responseOrException as CoreResponseData;
2909  WebException ex = responseOrException as WebException;
2910  object obj = Interlocked.CompareExchange(ref _CoreResponse, responseOrException, DBNull.Value);
2911  if (obj != null)
2912  {
2913  if (obj.GetType() == typeof(CoreResponseData))
2914  {
2915  if (coreResponseData != null)
2916  {
2917  throw new InternalException();
2918  }
2919  if (ex != null && ex.InternalStatus != WebExceptionInternalStatus.ServicePointFatal && ex.InternalStatus != 0)
2920  {
2921  return;
2922  }
2923  }
2924  else if (obj.GetType() != typeof(DBNull))
2925  {
2926  if (coreResponseData == null)
2927  {
2928  throw new InternalException();
2929  }
2930  ICloseEx closeEx = coreResponseData.m_ConnectStream as ICloseEx;
2931  if (closeEx != null)
2932  {
2933  closeEx.CloseEx(CloseExState.Silent);
2934  }
2935  else
2936  {
2937  coreResponseData.m_ConnectStream.Close();
2938  }
2939  return;
2940  }
2941  }
2942  if (obj == DBNull.Value)
2943  {
2944  if (!Async)
2945  {
2946  LazyAsyncResult connectionAsyncResult = ConnectionAsyncResult;
2947  LazyAsyncResult connectionReaderAsyncResult = ConnectionReaderAsyncResult;
2948  connectionAsyncResult.InvokeCallback(responseOrException);
2949  connectionReaderAsyncResult.InvokeCallback(responseOrException);
2950  }
2951  else if (!AllowWriteStreamBuffering && IsOutstandingGetRequestStream && FinishContinueWait())
2952  {
2953  if (coreResponseData != null)
2954  {
2955  SetResponse(coreResponseData);
2956  }
2957  else
2958  {
2959  SetResponse(ex);
2960  }
2961  }
2962  return;
2963  }
2964  if (obj != null)
2965  {
2966  Exception ex2 = responseOrException as Exception;
2967  if (ex2 != null)
2968  {
2969  SetResponse(ex2);
2970  return;
2971  }
2972  throw new InternalException();
2973  }
2974  obj = Interlocked.CompareExchange(ref _CoreResponse, responseOrException, null);
2975  if (obj != null && coreResponseData != null)
2976  {
2977  ICloseEx closeEx2 = coreResponseData.m_ConnectStream as ICloseEx;
2978  if (closeEx2 != null)
2979  {
2980  closeEx2.CloseEx(CloseExState.Silent);
2981  }
2982  else
2983  {
2984  coreResponseData.m_ConnectStream.Close();
2985  }
2986  return;
2987  }
2988  if (!Async)
2989  {
2990  throw new InternalException();
2991  }
2992  FinishContinueWait();
2993  if (coreResponseData != null)
2994  {
2995  SetResponse(coreResponseData);
2996  }
2997  else
2998  {
2999  SetResponse(responseOrException as Exception);
3000  }
3001  }
3002 
3003  private void SetResponse(CoreResponseData coreResponseData)
3004  {
3005  try
3006  {
3007  if (!Async)
3008  {
3009  LazyAsyncResult connectionAsyncResult = ConnectionAsyncResult;
3010  LazyAsyncResult connectionReaderAsyncResult = ConnectionReaderAsyncResult;
3011  connectionAsyncResult.InvokeCallback(coreResponseData);
3012  connectionReaderAsyncResult.InvokeCallback(coreResponseData);
3013  }
3014  if (coreResponseData != null)
3015  {
3016  if (coreResponseData.m_ConnectStream.CanTimeout)
3017  {
3018  coreResponseData.m_ConnectStream.WriteTimeout = ReadWriteTimeout;
3019  coreResponseData.m_ConnectStream.ReadTimeout = ReadWriteTimeout;
3020  }
3021  _HttpResponse = new HttpWebResponse(GetRemoteResourceUri(), CurrentMethod, coreResponseData, _MediaType, UsesProxySemantics, AutomaticDecompression, IsWebSocketRequest, ConnectionGroupName);
3022  if (Logging.On)
3023  {
3024  Logging.Associate(Logging.Web, this, coreResponseData.m_ConnectStream);
3025  }
3026  if (Logging.On)
3027  {
3028  Logging.Associate(Logging.Web, this, _HttpResponse);
3029  }
3030  ProcessResponse();
3031  }
3032  else
3033  {
3034  Abort(null, 1);
3035  }
3036  }
3037  catch (Exception exception)
3038  {
3039  Abort(exception, 2);
3040  }
3041  }
3042 
3043  private void ProcessResponse()
3044  {
3045  HttpProcessingResult httpProcessingResult = HttpProcessingResult.Continue;
3046  Exception exception = null;
3047  if (DoSubmitRequestProcessing(ref exception) == HttpProcessingResult.Continue)
3048  {
3049  CancelTimer();
3050  object result = (exception != null) ? ((ISerializable)exception) : ((ISerializable)_HttpResponse);
3051  if (_ReadAResult == null)
3052  {
3053  lock (this)
3054  {
3055  if (_ReadAResult == null)
3056  {
3057  _ReadAResult = new LazyAsyncResult(null, null, null);
3058  }
3059  }
3060  }
3061  try
3062  {
3063  FinishRequest(_HttpResponse, exception);
3064  _ReadAResult.InvokeCallback(result);
3065  try
3066  {
3067  SetRequestContinue();
3068  }
3069  catch
3070  {
3071  }
3072  }
3073  catch (Exception exception2)
3074  {
3075  Abort(exception2, 1);
3076  throw;
3077  }
3078  finally
3079  {
3080  if (exception == null && _ReadAResult.Result != _HttpResponse)
3081  {
3082  WebException ex = _ReadAResult.Result as WebException;
3083  if (ex != null && ex.Response != null)
3084  {
3085  _HttpResponse.Abort();
3086  }
3087  }
3088  }
3089  }
3090  }
3091 
3092  private void SetResponse(Exception E)
3093  {
3094  HttpProcessingResult httpProcessingResult = HttpProcessingResult.Continue;
3095  WebException ex = HaveResponse ? (_ReadAResult.Result as WebException) : null;
3096  WebException ex2 = E as WebException;
3097  if (ex != null && (ex.InternalStatus == WebExceptionInternalStatus.RequestFatal || ex.InternalStatus == WebExceptionInternalStatus.ServicePointFatal) && (ex2 == null || ex2.InternalStatus != 0))
3098  {
3099  E = ex;
3100  }
3101  else
3102  {
3103  ex = ex2;
3104  }
3105  if (E != null && Logging.On)
3106  {
3107  Logging.Exception(Logging.Web, this, "", ex);
3108  }
3109  try
3110  {
3111  if (ex != null && (ex.InternalStatus == WebExceptionInternalStatus.Isolated || ex.InternalStatus == WebExceptionInternalStatus.ServicePointFatal || (ex.InternalStatus == WebExceptionInternalStatus.Recoverable && !m_OnceFailed)))
3112  {
3113  if (ex.InternalStatus == WebExceptionInternalStatus.Recoverable)
3114  {
3115  m_OnceFailed = true;
3116  }
3117  Pipelined = false;
3118  if (_SubmitWriteStream != null && _OldSubmitWriteStream == null && _SubmitWriteStream.BufferOnly)
3119  {
3120  _OldSubmitWriteStream = _SubmitWriteStream;
3121  }
3122  httpProcessingResult = DoSubmitRequestProcessing(ref E);
3123  }
3124  }
3125  catch (Exception ex3)
3126  {
3127  if (NclUtilities.IsFatal(ex3))
3128  {
3129  throw;
3130  }
3131  httpProcessingResult = HttpProcessingResult.Continue;
3132  E = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), ex3, WebExceptionStatus.RequestCanceled, _HttpResponse);
3133  }
3134  finally
3135  {
3136  if (httpProcessingResult == HttpProcessingResult.Continue)
3137  {
3138  CancelTimer();
3139  if (!(E is WebException) && !(E is SecurityException))
3140  {
3141  E = ((_HttpResponse != null) ? new WebException(SR.GetString("net_servererror", NetRes.GetWebStatusCodeString(ResponseStatusCode, _HttpResponse.StatusDescription)), E, WebExceptionStatus.ProtocolError, _HttpResponse) : new WebException(E.Message, E));
3142  }
3143  LazyAsyncResult lazyAsyncResult = null;
3144  HttpWebResponse httpResponse = _HttpResponse;
3145  LazyAsyncResult writeAResult;
3146  lock (this)
3147  {
3148  writeAResult = _WriteAResult;
3149  if (_ReadAResult == null)
3150  {
3151  _ReadAResult = new LazyAsyncResult(null, null, null, E);
3152  }
3153  else
3154  {
3155  lazyAsyncResult = _ReadAResult;
3156  }
3157  }
3158  try
3159  {
3160  FinishRequest(httpResponse, E);
3161  try
3162  {
3163  writeAResult?.InvokeCallback(E);
3164  }
3165  finally
3166  {
3167  lazyAsyncResult?.InvokeCallback(E);
3168  }
3169  }
3170  finally
3171  {
3172  (_ReadAResult.Result as HttpWebResponse)?.Abort();
3173  if (base.CacheProtocol != null)
3174  {
3175  base.CacheProtocol.Abort();
3176  }
3177  }
3178  }
3179  }
3180  }
3181 
3182  internal override ContextAwareResult GetConnectingContext()
3183  {
3184  if (!Async)
3185  {
3186  return null;
3187  }
3188  ContextAwareResult contextAwareResult = ((HttpWriteMode == HttpWriteMode.None || _OldSubmitWriteStream != null || _WriteAResult == null || _WriteAResult.IsCompleted) ? _ReadAResult : _WriteAResult) as ContextAwareResult;
3189  if (contextAwareResult == null)
3190  {
3191  throw new InternalException();
3192  }
3193  return contextAwareResult;
3194  }
3195 
3196  internal override ContextAwareResult GetWritingContext()
3197  {
3198  if (!Async)
3199  {
3200  return null;
3201  }
3202  ContextAwareResult contextAwareResult = _WriteAResult as ContextAwareResult;
3203  if (contextAwareResult == null || contextAwareResult.InternalPeekCompleted || HttpWriteMode == HttpWriteMode.None || HttpWriteMode == HttpWriteMode.Buffer || m_PendingReturnResult == DBNull.Value || m_OriginallyBuffered)
3204  {
3205  contextAwareResult = (_ReadAResult as ContextAwareResult);
3206  }
3207  if (contextAwareResult == null)
3208  {
3209  throw new InternalException();
3210  }
3211  return contextAwareResult;
3212  }
3213 
3214  internal override ContextAwareResult GetReadingContext()
3215  {
3216  if (!Async)
3217  {
3218  return null;
3219  }
3220  ContextAwareResult contextAwareResult = _ReadAResult as ContextAwareResult;
3221  if (contextAwareResult == null)
3222  {
3223  contextAwareResult = (_WriteAResult as ContextAwareResult);
3224  if (contextAwareResult == null)
3225  {
3226  throw new InternalException();
3227  }
3228  }
3229  return contextAwareResult;
3230  }
3231 
3232  private void BeginSubmitRequest()
3233  {
3234  SubmitRequest(FindServicePoint(forceFind: false));
3235  }
3236 
3237  private void SubmitRequest(ServicePoint servicePoint)
3238  {
3239  if (!Async)
3240  {
3241  _ConnectionAResult = new LazyAsyncResult(this, null, null);
3242  _ConnectionReaderAResult = new LazyAsyncResult(this, null, null);
3243  OpenWriteSideResponseWindow();
3244  }
3245  if (_Timer == null && !Async)
3246  {
3247  _Timer = TimerQueue.CreateTimer(s_TimeoutCallback, this);
3248  }
3249  try
3250  {
3251  if (_SubmitWriteStream != null && _SubmitWriteStream.IsPostStream)
3252  {
3253  if (_OldSubmitWriteStream == null && !_SubmitWriteStream.ErrorInStream && AllowWriteStreamBuffering)
3254  {
3255  _OldSubmitWriteStream = _SubmitWriteStream;
3256  }
3257  _WriteBufferLength = 0;
3258  }
3259  m_Retry = false;
3260  if (PreAuthenticate)
3261  {
3262  if (UsesProxySemantics && _Proxy != null && _Proxy.Credentials != null)
3263  {
3264  ProxyAuthenticationState.PreAuthIfNeeded(this, _Proxy.Credentials);
3265  }
3266  if (Credentials != null)
3267  {
3268  ServerAuthenticationState.PreAuthIfNeeded(this, Credentials);
3269  }
3270  }
3271  if (WriteBufferLength == 0)
3272  {
3273  UpdateHeaders();
3274  }
3275  if (!CheckCacheRetrieveBeforeSubmit())
3276  {
3277  servicePoint.SubmitRequest(this, GetConnectionGroupLine());
3278  }
3279  }
3280  finally
3281  {
3282  if (!Async)
3283  {
3284  CheckWriteSideResponseProcessing();
3285  }
3286  }
3287  }
3288 
3289  private bool CheckCacheRetrieveBeforeSubmit()
3290  {
3291  if (base.CacheProtocol == null)
3292  {
3293  return false;
3294  }
3295  try
3296  {
3297  Uri uri = GetRemoteResourceUri();
3298  if (uri.Fragment.Length != 0)
3299  {
3300  uri = new Uri(uri.GetParts(UriComponents.Scheme | UriComponents.UserInfo | UriComponents.Host | UriComponents.Port | UriComponents.Path | UriComponents.Query, UriFormat.SafeUnescaped));
3301  }
3302  base.CacheProtocol.GetRetrieveStatus(uri, this);
3303  if (base.CacheProtocol.ProtocolStatus == CacheValidationStatus.Fail)
3304  {
3305  throw base.CacheProtocol.ProtocolException;
3306  }
3307  if (base.CacheProtocol.ProtocolStatus != CacheValidationStatus.ReturnCachedResponse)
3308  {
3309  return false;
3310  }
3311  if (HttpWriteMode != HttpWriteMode.None)
3312  {
3313  throw new NotSupportedException(SR.GetString("net_cache_not_supported_body"));
3314  }
3315  HttpRequestCacheValidator httpRequestCacheValidator = (HttpRequestCacheValidator)base.CacheProtocol.Validator;
3316  CoreResponseData coreResponseData = new CoreResponseData();
3317  coreResponseData.m_IsVersionHttp11 = httpRequestCacheValidator.CacheHttpVersion.Equals(HttpVersion.Version11);
3318  coreResponseData.m_StatusCode = httpRequestCacheValidator.CacheStatusCode;
3319  coreResponseData.m_StatusDescription = httpRequestCacheValidator.CacheStatusDescription;
3320  coreResponseData.m_ResponseHeaders = httpRequestCacheValidator.CacheHeaders;
3321  coreResponseData.m_ContentLength = base.CacheProtocol.ResponseStreamLength;
3322  coreResponseData.m_ConnectStream = base.CacheProtocol.ResponseStream;
3323  _HttpResponse = new HttpWebResponse(GetRemoteResourceUri(), CurrentMethod, coreResponseData, _MediaType, UsesProxySemantics, AutomaticDecompression, IsWebSocketRequest, ConnectionGroupName);
3324  _HttpResponse.InternalSetFromCache = true;
3325  _HttpResponse.InternalSetIsCacheFresh = (httpRequestCacheValidator.CacheFreshnessStatus != CacheFreshnessStatus.Stale);
3326  ProcessResponse();
3327  return true;
3328  }
3329  catch (Exception exception)
3330  {
3331  Abort(exception, 1);
3332  throw;
3333  }
3334  }
3335 
3336  private bool CheckCacheRetrieveOnResponse()
3337  {
3338  if (base.CacheProtocol == null)
3339  {
3340  return true;
3341  }
3342  if (base.CacheProtocol.ProtocolStatus == CacheValidationStatus.Fail)
3343  {
3344  throw base.CacheProtocol.ProtocolException;
3345  }
3346  Stream responseStream = _HttpResponse.ResponseStream;
3347  base.CacheProtocol.GetRevalidateStatus(_HttpResponse, _HttpResponse.ResponseStream);
3348  if (base.CacheProtocol.ProtocolStatus == CacheValidationStatus.RetryResponseFromServer)
3349  {
3350  return false;
3351  }
3352  if (base.CacheProtocol.ProtocolStatus != CacheValidationStatus.ReturnCachedResponse && base.CacheProtocol.ProtocolStatus != CacheValidationStatus.CombineCachedAndServerResponse)
3353  {
3354  return true;
3355  }
3356  if (HttpWriteMode != HttpWriteMode.None)
3357  {
3358  throw new NotSupportedException(SR.GetString("net_cache_not_supported_body"));
3359  }
3360  CoreResponseData coreResponseData = new CoreResponseData();
3361  HttpRequestCacheValidator httpRequestCacheValidator = (HttpRequestCacheValidator)base.CacheProtocol.Validator;
3362  coreResponseData.m_IsVersionHttp11 = httpRequestCacheValidator.CacheHttpVersion.Equals(HttpVersion.Version11);
3363  coreResponseData.m_StatusCode = httpRequestCacheValidator.CacheStatusCode;
3364  coreResponseData.m_StatusDescription = httpRequestCacheValidator.CacheStatusDescription;
3365  coreResponseData.m_ResponseHeaders = ((base.CacheProtocol.ProtocolStatus == CacheValidationStatus.CombineCachedAndServerResponse) ? new WebHeaderCollection(httpRequestCacheValidator.CacheHeaders) : httpRequestCacheValidator.CacheHeaders);
3366  coreResponseData.m_ContentLength = base.CacheProtocol.ResponseStreamLength;
3367  coreResponseData.m_ConnectStream = base.CacheProtocol.ResponseStream;
3368  _HttpResponse = new HttpWebResponse(GetRemoteResourceUri(), CurrentMethod, coreResponseData, _MediaType, UsesProxySemantics, AutomaticDecompression, IsWebSocketRequest, ConnectionGroupName);
3369  if (base.CacheProtocol.ProtocolStatus == CacheValidationStatus.ReturnCachedResponse)
3370  {
3371  _HttpResponse.InternalSetFromCache = true;
3372  _HttpResponse.InternalSetIsCacheFresh = base.CacheProtocol.IsCacheFresh;
3373  if (responseStream != null)
3374  {
3375  try
3376  {
3377  responseStream.Close();
3378  }
3379  catch
3380  {
3381  }
3382  }
3383  }
3384  return true;
3385  }
3386 
3387  private void CheckCacheUpdateOnResponse()
3388  {
3389  if (base.CacheProtocol != null)
3390  {
3391  if (base.CacheProtocol.GetUpdateStatus(_HttpResponse, _HttpResponse.ResponseStream) == CacheValidationStatus.UpdateResponseInformation)
3392  {
3393  _HttpResponse.ResponseStream = base.CacheProtocol.ResponseStream;
3394  }
3395  else if (base.CacheProtocol.ProtocolStatus == CacheValidationStatus.Fail)
3396  {
3397  throw base.CacheProtocol.ProtocolException;
3398  }
3399  }
3400  }
3401 
3402  private void EndSubmitRequest()
3403  {
3404  try
3405  {
3406  if (HttpWriteMode == HttpWriteMode.Buffer)
3407  {
3408  InvokeGetRequestStreamCallback();
3409  }
3410  else
3411  {
3412  if (WriteBufferLength == 0)
3413  {
3414  long value = SwitchToContentLength();
3415  SerializeHeaders();
3416  PostSwitchToContentLength(value);
3417  }
3418  _SubmitWriteStream.WriteHeaders(Async);
3419  }
3420  }
3421  catch
3422  {
3423  _SubmitWriteStream?.CallDone();
3424  throw;
3425  }
3426  finally
3427  {
3428  if (!Async)
3429  {
3430  CheckWriteSideResponseProcessing();
3431  }
3432  }
3433  }
3434 
3435  internal bool EndWriteHeaders(bool async)
3436  {
3437  try
3438  {
3439  if (ShouldWaitFor100Continue())
3440  {
3441  return !async;
3442  }
3443  if (FinishContinueWait() && CompleteContinueGate())
3444  {
3445  EndWriteHeaders_Part2();
3446  }
3447  }
3448  catch
3449  {
3450  _SubmitWriteStream?.CallDone();
3451  throw;
3452  }
3453  return true;
3454  }
3455 
3456  internal bool ShouldWaitFor100Continue()
3457  {
3458  if ((ContentLength > 0 || HttpWriteMode == HttpWriteMode.Chunked) && ExpectContinue)
3459  {
3460  return _ServicePoint.Understands100Continue;
3461  }
3462  return false;
3463  }
3464 
3465  private static void ContinueTimeoutCallback(TimerThread.Timer timer, int timeNoticed, object context)
3466  {
3467  HttpWebRequest httpWebRequest = (HttpWebRequest)context;
3468  if (httpWebRequest.HttpWriteMode != HttpWriteMode.None && httpWebRequest.FinishContinueWait() && httpWebRequest.CompleteContinueGate())
3469  {
3470  ThreadPool.UnsafeQueueUserWorkItem(s_EndWriteHeaders_Part2Callback, httpWebRequest);
3471  }
3472  }
3473 
3474  internal void StartContinueWait()
3475  {
3476  bool flag = m_ContinueGate.Trigger(exclusive: true);
3477  }
3478 
3479  internal void StartAsync100ContinueTimer()
3480  {
3481  if (m_ContinueGate.StartTriggering(exclusive: true))
3482  {
3483  try
3484  {
3485  if (ShouldWaitFor100Continue())
3486  {
3487  m_ContinueTimer = ContinueTimerQueue.CreateTimer(s_ContinueTimeoutCallback, this);
3488  }
3489  }
3490  finally
3491  {
3492  m_ContinueGate.FinishTriggering();
3493  }
3494  }
3495  }
3496 
3497  internal bool FinishContinueWait()
3498  {
3499  if (m_ContinueGate.StartSignaling(exclusive: false))
3500  {
3501  try
3502  {
3503  TimerThread.Timer continueTimer = m_ContinueTimer;
3504  m_ContinueTimer = null;
3505  continueTimer?.Cancel();
3506  }
3507  finally
3508  {
3509  m_ContinueGate.FinishSignaling();
3510  }
3511  return true;
3512  }
3513  return false;
3514  }
3515 
3516  private bool CompleteContinueGate()
3517  {
3518  return m_ContinueGate.Complete();
3519  }
3520 
3521  private static void EndWriteHeaders_Part2Wrapper(object state)
3522  {
3523  ((HttpWebRequest)state).EndWriteHeaders_Part2();
3524  }
3525 
3526  internal void EndWriteHeaders_Part2()
3527  {
3528  try
3529  {
3530  ConnectStream submitWriteStream = _SubmitWriteStream;
3531  if (HttpWriteMode != HttpWriteMode.None)
3532  {
3533  m_BodyStarted = true;
3534  if (AllowWriteStreamBuffering || _resendRequestContent != null)
3535  {
3536  if (submitWriteStream.BufferOnly)
3537  {
3538  _OldSubmitWriteStream = submitWriteStream;
3539  }
3540  if (_OldSubmitWriteStream != null || (UserRetrievedWriteStream && _resendRequestContent != null))
3541  {
3542  if (_resendRequestContent == null)
3543  {
3544  submitWriteStream.ResubmitWrite(_OldSubmitWriteStream, NtlmKeepAlive && ContentLength == 0);
3545  }
3546  else if (NtlmKeepAlive && (ContentLength == 0L || HttpWriteMode == HttpWriteMode.Chunked))
3547  {
3548  if (ContentLength == 0L)
3549  {
3550  submitWriteStream.BytesLeftToWrite = 0L;
3551  }
3552  }
3553  else
3554  {
3555  if (HttpWriteMode != HttpWriteMode.Chunked)
3556  {
3557  submitWriteStream.BytesLeftToWrite = _originalContentLength;
3558  }
3559  try
3560  {
3561  _resendRequestContent(submitWriteStream);
3562  }
3563  catch (Exception exception)
3564  {
3565  Abort(exception, 1);
3566  }
3567  }
3568  submitWriteStream.CloseInternal(internalCall: true);
3569  }
3570  }
3571  }
3572  else
3573  {
3574  if (submitWriteStream != null)
3575  {
3576  submitWriteStream.CloseInternal(internalCall: true);
3577  submitWriteStream = null;
3578  }
3579  _OldSubmitWriteStream = null;
3580  }
3581  InvokeGetRequestStreamCallback();
3582  }
3583  catch
3584  {
3585  _SubmitWriteStream?.CallDone();
3586  throw;
3587  }
3588  }
3589 
3590  private int GenerateConnectRequestLine(int headersSize)
3591  {
3592  int num = 0;
3593  HostHeaderString hostHeaderString = new HostHeaderString(GetSafeHostAndPort(addDefaultPort: true, forcePunycode: true));
3594  int writeBuffer = CurrentMethod.Name.Length + hostHeaderString.ByteCount + 12 + headersSize;
3595  SetWriteBuffer(writeBuffer);
3596  num = Encoding.ASCII.GetBytes(CurrentMethod.Name, 0, CurrentMethod.Name.Length, WriteBuffer, 0);
3597  WriteBuffer[num++] = 32;
3598  hostHeaderString.Copy(WriteBuffer, num);
3599  num += hostHeaderString.ByteCount;
3600  WriteBuffer[num++] = 32;
3601  return num;
3602  }
3603 
3604  private string GetSafeHostAndPort(bool addDefaultPort, bool forcePunycode)
3605  {
3606  if (IsTunnelRequest)
3607  {
3608  return GetSafeHostAndPort(_OriginUri, addDefaultPort, forcePunycode);
3609  }
3610  return GetSafeHostAndPort(_Uri, addDefaultPort, forcePunycode);
3611  }
3612 
3613  private static string GetSafeHostAndPort(Uri sourceUri, bool addDefaultPort, bool forcePunycode)
3614  {
3615  string hostName = (sourceUri.HostNameType != UriHostNameType.IPv6) ? (forcePunycode ? sourceUri.IdnHost : sourceUri.DnsSafeHost) : ("[" + TrimScopeID(sourceUri.DnsSafeHost) + "]");
3616  return GetHostAndPortString(hostName, sourceUri.Port, addDefaultPort || !sourceUri.IsDefaultPort);
3617  }
3618 
3619  private static string GetHostAndPortString(string hostName, int port, bool addPort)
3620  {
3621  if (addPort)
3622  {
3623  return hostName + ":" + port;
3624  }
3625  return hostName;
3626  }
3627 
3628  private bool TryGetHostUri(string hostName, out Uri hostUri)
3629  {
3630  StringBuilder stringBuilder = new StringBuilder(_Uri.Scheme);
3631  stringBuilder.Append("://");
3632  stringBuilder.Append(hostName);
3633  stringBuilder.Append(_Uri.PathAndQuery);
3634  return Uri.TryCreate(stringBuilder.ToString(), UriKind.Absolute, out hostUri);
3635  }
3636 
3637  private static string TrimScopeID(string s)
3638  {
3639  int num = s.LastIndexOf('%');
3640  if (num > 0)
3641  {
3642  return s.Substring(0, num);
3643  }
3644  return s;
3645  }
3646 
3647  private int GenerateProxyRequestLine(int headersSize)
3648  {
3649  if ((object)_Uri.Scheme == Uri.UriSchemeFtp)
3650  {
3651  return GenerateFtpProxyRequestLine(headersSize);
3652  }
3653  int num = 0;
3654  string components = _Uri.GetComponents(UriComponents.Scheme | UriComponents.KeepDelimiter, UriFormat.UriEscaped);
3655  HostHeaderString hostHeaderString = new HostHeaderString(GetSafeHostAndPort(addDefaultPort: false, forcePunycode: true));
3656  string components2 = _Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped);
3657  int writeBuffer = CurrentMethod.Name.Length + components.Length + hostHeaderString.ByteCount + components2.Length + 12 + headersSize;
3658  SetWriteBuffer(writeBuffer);
3659  num = Encoding.ASCII.GetBytes(CurrentMethod.Name, 0, CurrentMethod.Name.Length, WriteBuffer, 0);
3660  WriteBuffer[num++] = 32;
3661  num += Encoding.ASCII.GetBytes(components, 0, components.Length, WriteBuffer, num);
3662  hostHeaderString.Copy(WriteBuffer, num);
3663  num += hostHeaderString.ByteCount;
3664  num += Encoding.ASCII.GetBytes(components2, 0, components2.Length, WriteBuffer, num);
3665  WriteBuffer[num++] = 32;
3666  return num;
3667  }
3668 
3669  private int GenerateFtpProxyRequestLine(int headersSize)
3670  {
3671  int num = 0;
3672  string components = _Uri.GetComponents(UriComponents.Scheme | UriComponents.KeepDelimiter, UriFormat.UriEscaped);
3673  string text = _Uri.GetComponents(UriComponents.UserInfo | UriComponents.KeepDelimiter, UriFormat.UriEscaped);
3674  HostHeaderString hostHeaderString = new HostHeaderString(GetSafeHostAndPort(addDefaultPort: false, forcePunycode: true));
3675  string components2 = _Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped);
3676  if (text == "")
3677  {
3678  string text2 = null;
3679  string text3 = null;
3680  NetworkCredential credential = Credentials.GetCredential(_Uri, "basic");
3681  if (credential != null && credential != FtpWebRequest.DefaultNetworkCredential)
3682  {
3683  text2 = credential.InternalGetDomainUserName();
3684  text3 = credential.InternalGetPassword();
3685  text3 = ((text3 == null) ? string.Empty : text3);
3686  }
3687  if (text2 != null)
3688  {
3689  text2 = text2.Replace(":", "%3A");
3690  text3 = text3.Replace(":", "%3A");
3691  text2 = text2.Replace("\\", "%5C");
3692  text3 = text3.Replace("\\", "%5C");
3693  text2 = text2.Replace("/", "%2F");
3694  text3 = text3.Replace("/", "%2F");
3695  text2 = text2.Replace("?", "%3F");
3696  text3 = text3.Replace("?", "%3F");
3697  text2 = text2.Replace("#", "%23");
3698  text3 = text3.Replace("#", "%23");
3699  text2 = text2.Replace("%", "%25");
3700  text3 = text3.Replace("%", "%25");
3701  text2 = text2.Replace("@", "%40");
3702  text3 = text3.Replace("@", "%40");
3703  text = text2 + ":" + text3 + "@";
3704  }
3705  }
3706  int writeBuffer = CurrentMethod.Name.Length + components.Length + text.Length + hostHeaderString.ByteCount + components2.Length + 12 + headersSize;
3707  SetWriteBuffer(writeBuffer);
3708  num = Encoding.ASCII.GetBytes(CurrentMethod.Name, 0, CurrentMethod.Name.Length, WriteBuffer, 0);
3709  WriteBuffer[num++] = 32;
3710  num += Encoding.ASCII.GetBytes(components, 0, components.Length, WriteBuffer, num);
3711  num += Encoding.ASCII.GetBytes(text, 0, text.Length, WriteBuffer, num);
3712  hostHeaderString.Copy(WriteBuffer, num);
3713  num += hostHeaderString.ByteCount;
3714  num += Encoding.ASCII.GetBytes(components2, 0, components2.Length, WriteBuffer, num);
3715  WriteBuffer[num++] = 32;
3716  return num;
3717  }
3718 
3719  private int GenerateRequestLine(int headersSize)
3720  {
3721  int num = 0;
3722  string pathAndQuery = _Uri.PathAndQuery;
3723  int writeBuffer = CurrentMethod.Name.Length + pathAndQuery.Length + 12 + headersSize;
3724  SetWriteBuffer(writeBuffer);
3725  num = Encoding.ASCII.GetBytes(CurrentMethod.Name, 0, CurrentMethod.Name.Length, WriteBuffer, 0);
3726  WriteBuffer[num++] = 32;
3727  num += Encoding.ASCII.GetBytes(pathAndQuery, 0, pathAndQuery.Length, WriteBuffer, num);
3728  WriteBuffer[num++] = 32;
3729  return num;
3730  }
3731 
3732  internal Uri GetRemoteResourceUri()
3733  {
3734  if (UseCustomHost)
3735  {
3736  return _HostUri;
3737  }
3738  return _Uri;
3739  }
3740 
3741  internal void UpdateHeaders()
3742  {
3743  bool flag = IsTunnelRequest && _OriginUri.Scheme == Uri.UriSchemeHttp;
3744  string s = (!UseCustomHost) ? GetSafeHostAndPort(flag, forcePunycode: false) : GetSafeHostAndPort(_HostUri, _HostHasPort | flag, forcePunycode: false);
3745  HostHeaderString hostHeaderString = new HostHeaderString(s);
3746  string @string = WebHeaderCollection.HeaderEncoding.GetString(hostHeaderString.Bytes, 0, hostHeaderString.ByteCount);
3747  _HttpRequestHeaders.ChangeInternal("Host", @string);
3748  if (_CookieContainer != null)
3749  {
3750  CookieModule.OnSendingHeaders(this);
3751  }
3752  }
3753 
3754  internal void SerializeHeaders()
3755  {
3756  if (HttpWriteMode != HttpWriteMode.None)
3757  {
3758  if (HttpWriteMode == HttpWriteMode.Chunked)
3759  {
3760  _HttpRequestHeaders.AddInternal("Transfer-Encoding", "chunked");
3761  }
3762  else if (ContentLength >= 0)
3763  {
3764  _HttpRequestHeaders.ChangeInternal("Content-Length", _ContentLength.ToString(NumberFormatInfo.InvariantInfo));
3765  }
3766  ExpectContinue = (ExpectContinue && !IsVersionHttp10 && ServicePoint.Expect100Continue);
3767  if ((ContentLength > 0 || HttpWriteMode == HttpWriteMode.Chunked) && ExpectContinue)
3768  {
3769  _HttpRequestHeaders.AddInternal("Expect", "100-continue");
3770  }
3771  }
3772  string text = _HttpRequestHeaders.Get("Accept-Encoding") ?? string.Empty;
3773  if ((AutomaticDecompression & DecompressionMethods.GZip) != 0 && text.IndexOf("gzip", StringComparison.OrdinalIgnoreCase) < 0)
3774  {
3775  if ((AutomaticDecompression & DecompressionMethods.Deflate) != 0 && text.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) < 0)
3776  {
3777  _HttpRequestHeaders.AddInternal("Accept-Encoding", "gzip, deflate");
3778  }
3779  else
3780  {
3781  _HttpRequestHeaders.AddInternal("Accept-Encoding", "gzip");
3782  }
3783  }
3784  else if ((AutomaticDecompression & DecompressionMethods.Deflate) != 0 && text.IndexOf("deflate", StringComparison.OrdinalIgnoreCase) < 0)
3785  {
3786  _HttpRequestHeaders.AddInternal("Accept-Encoding", "deflate");
3787  }
3788  string name = "Connection";
3789  if (UsesProxySemantics || IsTunnelRequest)
3790  {
3791  _HttpRequestHeaders.RemoveInternal("Connection");
3792  name = "Proxy-Connection";
3793  if (!ValidationHelper.IsBlankString(Connection))
3794  {
3795  _HttpRequestHeaders.AddInternal("Proxy-Connection", _HttpRequestHeaders["Connection"]);
3796  }
3797  }
3798  else
3799  {
3800  _HttpRequestHeaders.RemoveInternal("Proxy-Connection");
3801  }
3802  if (IsWebSocketRequest)
3803  {
3804  string text2 = _HttpRequestHeaders.Get("Connection") ?? string.Empty;
3805  if (text2.IndexOf("Upgrade", StringComparison.OrdinalIgnoreCase) < 0)
3806  {
3807  _HttpRequestHeaders.AddInternal("Connection", "Upgrade");
3808  }
3809  }
3810  if (KeepAlive || NtlmKeepAlive)
3811  {
3812  if (IsVersionHttp10 || (int)ServicePoint.HttpBehaviour <= 1)
3813  {
3814  _HttpRequestHeaders.AddInternal((UsesProxySemantics || IsTunnelRequest) ? "Proxy-Connection" : "Connection", "Keep-Alive");
3815  }
3816  }
3817  else if (!IsVersionHttp10)
3818  {
3819  _HttpRequestHeaders.AddInternal(name, "Close");
3820  }
3821  string text3 = _HttpRequestHeaders.ToString();
3822  int byteCount = WebHeaderCollection.HeaderEncoding.GetByteCount(text3);
3823  int num = CurrentMethod.ConnectRequest ? GenerateConnectRequestLine(byteCount) : ((!UsesProxySemantics) ? GenerateRequestLine(byteCount) : GenerateProxyRequestLine(byteCount));
3824  Buffer.BlockCopy(HttpBytes, 0, WriteBuffer, num, HttpBytes.Length);
3825  num += HttpBytes.Length;
3826  WriteBuffer[num++] = 49;
3827  WriteBuffer[num++] = 46;
3828  WriteBuffer[num++] = (byte)(IsVersionHttp10 ? 48 : 49);
3829  WriteBuffer[num++] = 13;
3830  WriteBuffer[num++] = 10;
3831  if (Logging.On)
3832  {
3833  Logging.PrintInfo(Logging.Web, this, "Request: " + Encoding.ASCII.GetString(WriteBuffer, 0, num));
3834  }
3835  WebHeaderCollection.HeaderEncoding.GetBytes(text3, 0, text3.Length, WriteBuffer, num);
3836  }
3837 
3839  [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
3840  [EditorBrowsable(EditorBrowsableState.Never)]
3842  {
3843  }
3844 
3845  internal HttpWebRequest(Uri uri, ServicePoint servicePoint)
3846  {
3847  if (Logging.On)
3848  {
3849  Logging.Enter(Logging.Web, this, "HttpWebRequest", uri);
3850  }
3851  CheckConnectPermission(uri, needExecutionContext: false);
3852  m_StartTimestamp = NetworkingPerfCounters.GetTimestamp();
3853  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.HttpWebRequestCreated);
3854  _HttpRequestHeaders = new WebHeaderCollection(WebHeaderCollectionType.HttpWebRequest);
3855  _Proxy = WebRequest.InternalDefaultWebProxy;
3856  _HttpWriteMode = HttpWriteMode.Unknown;
3857  _MaximumAllowedRedirections = 50;
3858  _Timeout = 100000;
3859  _TimerQueue = WebRequest.DefaultTimerQueue;
3860  _ReadWriteTimeout = 300000;
3861  _MaximumResponseHeadersLength = DefaultMaximumResponseHeadersLength;
3862  _ContentLength = -1L;
3863  _originalContentLength = -1L;
3864  _OriginVerb = KnownHttpVerb.Get;
3865  _OriginUri = uri;
3866  _Uri = _OriginUri;
3867  _ServicePoint = servicePoint;
3868  _RequestIsAsync = TriState.Unspecified;
3869  m_ContinueTimeout = 350;
3870  m_ContinueTimerQueue = s_ContinueTimerQueue;
3871  SetupCacheProtocol(_OriginUri);
3872  if (Logging.On)
3873  {
3874  Logging.Exit(Logging.Web, this, "HttpWebRequest", null);
3875  }
3876  }
3877 
3878  internal HttpWebRequest(Uri proxyUri, Uri requestUri, HttpWebRequest orginalRequest)
3879  : this(proxyUri, null)
3880  {
3881  _OriginVerb = KnownHttpVerb.Parse("CONNECT");
3882  Pipelined = false;
3883  _OriginUri = requestUri;
3884  IsTunnelRequest = true;
3885  _ConnectionGroupName = ServicePointManager.SpecialConnectGroupName + "(" + UniqueGroupId + ")";
3886  m_InternalConnectionGroup = true;
3887  ServerAuthenticationState = new AuthenticationState(isProxyAuth: true);
3888  base.CacheProtocol = null;
3889  m_ContinueTimeout = 350;
3890  m_ContinueTimerQueue = s_ContinueTimerQueue;
3891  }
3892 
3893  internal HttpWebRequest(Uri uri, bool returnResponseOnFailureStatusCode, string connectionGroupName, Action<Stream> resendRequestContent)
3894  : this(uri, null)
3895  {
3896  if (Logging.On)
3897  {
3898  Logging.Enter(Logging.Web, this, "HttpWebRequest", "uri: '" + uri + "', connectionGroupName: '" + connectionGroupName + "'");
3899  }
3900  _returnResponseOnFailureStatusCode = returnResponseOnFailureStatusCode;
3901  _resendRequestContent = resendRequestContent;
3902  _Booleans &= ~Booleans.AllowWriteStreamBuffering;
3903  m_InternalConnectionGroup = true;
3904  _ConnectionGroupName = connectionGroupName;
3905  if (Logging.On)
3906  {
3907  Logging.Exit(Logging.Web, this, "HttpWebRequest", null);
3908  }
3909  }
3910 
3911  internal HttpWebRequest(Uri uri, ServicePoint servicePoint, bool isWebSocketRequest, string connectionGroupName)
3912  : this(uri, servicePoint)
3913  {
3914  IsWebSocketRequest = isWebSocketRequest;
3915  _ConnectionGroupName = connectionGroupName;
3916  }
3917 
3921  [Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?linkid=14202")]
3922  [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
3923  protected HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext)
3924  : base(serializationInfo, streamingContext)
3925  {
3926  ExceptionHelper.WebPermissionUnrestricted.Demand();
3927  if (Logging.On)
3928  {
3929  Logging.Enter(Logging.Web, this, "HttpWebRequest", serializationInfo);
3930  }
3931  _HttpRequestHeaders = (WebHeaderCollection)serializationInfo.GetValue("_HttpRequestHeaders", typeof(WebHeaderCollection));
3932  _Proxy = (IWebProxy)serializationInfo.GetValue("_Proxy", typeof(IWebProxy));
3933  KeepAlive = serializationInfo.GetBoolean("_KeepAlive");
3934  Pipelined = serializationInfo.GetBoolean("_Pipelined");
3935  AllowAutoRedirect = serializationInfo.GetBoolean("_AllowAutoRedirect");
3936  if (!serializationInfo.GetBoolean("_AllowWriteStreamBuffering"))
3937  {
3938  _Booleans &= ~Booleans.AllowWriteStreamBuffering;
3939  }
3940  HttpWriteMode = (HttpWriteMode)serializationInfo.GetInt32("_HttpWriteMode");
3941  _MaximumAllowedRedirections = serializationInfo.GetInt32("_MaximumAllowedRedirections");
3942  _AutoRedirects = serializationInfo.GetInt32("_AutoRedirects");
3943  _Timeout = serializationInfo.GetInt32("_Timeout");
3944  m_ContinueTimeout = 350;
3945  m_ContinueTimerQueue = s_ContinueTimerQueue;
3946  try
3947  {
3948  _ReadWriteTimeout = serializationInfo.GetInt32("_ReadWriteTimeout");
3949  }
3950  catch
3951  {
3952  _ReadWriteTimeout = 300000;
3953  }
3954  try
3955  {
3956  _MaximumResponseHeadersLength = serializationInfo.GetInt32("_MaximumResponseHeadersLength");
3957  }
3958  catch
3959  {
3960  _MaximumResponseHeadersLength = DefaultMaximumResponseHeadersLength;
3961  }
3962  _ContentLength = serializationInfo.GetInt64("_ContentLength");
3963  _MediaType = serializationInfo.GetString("_MediaType");
3964  _OriginVerb = KnownHttpVerb.Parse(serializationInfo.GetString("_OriginVerb"));
3965  _ConnectionGroupName = serializationInfo.GetString("_ConnectionGroupName");
3966  ProtocolVersion = (Version)serializationInfo.GetValue("_Version", typeof(Version));
3967  _OriginUri = (Uri)serializationInfo.GetValue("_OriginUri", typeof(Uri));
3968  SetupCacheProtocol(_OriginUri);
3969  if (Logging.On)
3970  {
3971  Logging.Exit(Logging.Web, this, "HttpWebRequest", null);
3972  }
3973  }
3974 
3978  [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter, SerializationFormatter = true)]
3979  void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
3980  {
3981  GetObjectData(serializationInfo, streamingContext);
3982  }
3983 
3987  [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
3988  protected override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
3989  {
3990  serializationInfo.AddValue("_HttpRequestHeaders", _HttpRequestHeaders, typeof(WebHeaderCollection));
3991  serializationInfo.AddValue("_Proxy", _Proxy, typeof(IWebProxy));
3992  serializationInfo.AddValue("_KeepAlive", KeepAlive);
3993  serializationInfo.AddValue("_Pipelined", Pipelined);
3994  serializationInfo.AddValue("_AllowAutoRedirect", AllowAutoRedirect);
3995  serializationInfo.AddValue("_AllowWriteStreamBuffering", AllowWriteStreamBuffering);
3996  serializationInfo.AddValue("_HttpWriteMode", HttpWriteMode);
3997  serializationInfo.AddValue("_MaximumAllowedRedirections", _MaximumAllowedRedirections);
3998  serializationInfo.AddValue("_AutoRedirects", _AutoRedirects);
3999  serializationInfo.AddValue("_Timeout", _Timeout);
4000  serializationInfo.AddValue("_ReadWriteTimeout", _ReadWriteTimeout);
4001  serializationInfo.AddValue("_MaximumResponseHeadersLength", _MaximumResponseHeadersLength);
4002  serializationInfo.AddValue("_ContentLength", ContentLength);
4003  serializationInfo.AddValue("_MediaType", _MediaType);
4004  serializationInfo.AddValue("_OriginVerb", _OriginVerb);
4005  serializationInfo.AddValue("_ConnectionGroupName", _ConnectionGroupName);
4006  serializationInfo.AddValue("_Version", ProtocolVersion, typeof(Version));
4007  serializationInfo.AddValue("_OriginUri", _OriginUri, typeof(Uri));
4008  base.GetObjectData(serializationInfo, streamingContext);
4009  }
4010 
4011  internal static StringBuilder GenerateConnectionGroup(string connectionGroupName, bool unsafeConnectionGroup, bool isInternalGroup)
4012  {
4013  StringBuilder stringBuilder = new StringBuilder(connectionGroupName);
4014  stringBuilder.Append(unsafeConnectionGroup ? "U>" : "S>");
4015  if (isInternalGroup)
4016  {
4017  stringBuilder.Append("I>");
4018  }
4019  return stringBuilder;
4020  }
4021 
4022  internal string GetConnectionGroupLine()
4023  {
4024  StringBuilder stringBuilder = GenerateConnectionGroup(_ConnectionGroupName, UnsafeAuthenticatedConnectionSharing, m_InternalConnectionGroup);
4025  if (_Uri.Scheme == Uri.UriSchemeHttps || IsTunnelRequest)
4026  {
4027  if (UsesProxy)
4028  {
4029  stringBuilder.Append(GetSafeHostAndPort(addDefaultPort: true, forcePunycode: false));
4030  stringBuilder.Append("$");
4031  }
4032  if (_ClientCertificates != null && ClientCertificates.Count > 0)
4033  {
4035  }
4037  {
4038  stringBuilder.Append("&");
4039  stringBuilder.Append(GetDelegateId(ServerCertificateValidationCallback));
4040  }
4041  }
4042  if (ProxyAuthenticationState.UniqueGroupId != null)
4043  {
4044  stringBuilder.Append(ProxyAuthenticationState.UniqueGroupId);
4045  }
4046  else if (ServerAuthenticationState.UniqueGroupId != null)
4047  {
4048  stringBuilder.Append(ServerAuthenticationState.UniqueGroupId);
4049  }
4050  return stringBuilder.ToString();
4051  }
4052 
4053  private static string GetDelegateId(RemoteCertificateValidationCallback callback)
4054  {
4055  try
4056  {
4057  new ReflectionPermission(PermissionState.Unrestricted).Assert();
4058  MethodInfo method = callback.Method;
4059  string name = callback.Method.Name;
4060  object target = callback.Target;
4061  string str = (target != null) ? (target.GetType().Name + "#" + target.GetHashCode().ToString(NumberFormatInfo.InvariantInfo)) : method.DeclaringType.FullName;
4062  return str + "::" + name;
4063  }
4064  finally
4065  {
4067  }
4068  }
4069 
4070  private bool CheckResubmitForAuth()
4071  {
4072  bool flag = false;
4073  bool flag2 = false;
4074  bool flag3 = false;
4075  if (UsesProxySemantics && _Proxy != null && _Proxy.Credentials != null)
4076  {
4077  try
4078  {
4079  flag |= ProxyAuthenticationState.AttemptAuthenticate(this, _Proxy.Credentials);
4080  }
4081  catch (Win32Exception)
4082  {
4083  if (!m_Extra401Retry)
4084  {
4085  throw;
4086  }
4087  flag3 = true;
4088  }
4089  flag2 = true;
4090  }
4091  if (Credentials != null && !flag3)
4092  {
4093  try
4094  {
4095  flag |= ServerAuthenticationState.AttemptAuthenticate(this, Credentials);
4096  }
4097  catch (Win32Exception)
4098  {
4099  if (!m_Extra401Retry)
4100  {
4101  throw;
4102  }
4103  flag = false;
4104  }
4105  flag2 = true;
4106  }
4107  if (!flag && flag2 && m_Extra401Retry)
4108  {
4109  ClearAuthenticatedConnectionResources();
4110  m_Extra401Retry = false;
4111  flag = true;
4112  }
4113  return flag;
4114  }
4115 
4116  private bool CheckResubmitForCache(ref Exception e)
4117  {
4118  if (!CheckCacheRetrieveOnResponse())
4119  {
4120  if (AllowAutoRedirect)
4121  {
4122  if (Logging.On)
4123  {
4124  Logging.PrintWarning(Logging.Web, this, "", SR.GetString("net_log_cache_validation_failed_resubmit"));
4125  }
4126  return true;
4127  }
4128  if (Logging.On)
4129  {
4130  Logging.PrintError(Logging.Web, this, "", SR.GetString("net_log_cache_refused_server_response"));
4131  }
4132  e = new InvalidOperationException(SR.GetString("net_cache_not_accept_response"));
4133  return false;
4134  }
4135  CheckCacheUpdateOnResponse();
4136  return false;
4137  }
4138 
4139  private void SetExceptionIfRequired(string message, ref Exception e)
4140  {
4141  SetExceptionIfRequired(message, null, ref e);
4142  }
4143 
4144  private void SetExceptionIfRequired(string message, Exception innerException, ref Exception e)
4145  {
4146  if (_returnResponseOnFailureStatusCode)
4147  {
4148  if (Logging.On)
4149  {
4150  if (innerException != null)
4151  {
4152  Logging.Exception(Logging.Web, this, "", innerException);
4153  }
4154  Logging.PrintWarning(Logging.Web, this, "", message);
4155  }
4156  }
4157  else
4158  {
4159  e = new WebException(message, innerException, WebExceptionStatus.ProtocolError, _HttpResponse);
4160  }
4161  }
4162 
4163  private bool CheckResubmit(ref Exception e, ref bool disableUpload)
4164  {
4165  bool flag = false;
4166  if (ResponseStatusCode == HttpStatusCode.Unauthorized || ResponseStatusCode == HttpStatusCode.ProxyAuthenticationRequired)
4167  {
4168  try
4169  {
4170  if (!(flag = CheckResubmitForAuth()))
4171  {
4172  SetExceptionIfRequired(SR.GetString("net_servererror", NetRes.GetWebStatusCodeString(ResponseStatusCode, _HttpResponse.StatusDescription)), ref e);
4173  return false;
4174  }
4175  }
4176  catch (Win32Exception innerException)
4177  {
4178  throw new WebException(SR.GetString("net_servererror", NetRes.GetWebStatusCodeString(ResponseStatusCode, _HttpResponse.StatusDescription)), innerException, WebExceptionStatus.ProtocolError, _HttpResponse);
4179  }
4180  }
4181  else
4182  {
4183  if (ServerAuthenticationState != null && ServerAuthenticationState.Authorization != null)
4184  {
4185  HttpWebResponse httpResponse = _HttpResponse;
4186  if (httpResponse != null)
4187  {
4188  httpResponse.InternalSetIsMutuallyAuthenticated = ServerAuthenticationState.Authorization.MutuallyAuthenticated;
4189  if (base.AuthenticationLevel == AuthenticationLevel.MutualAuthRequired && !httpResponse.IsMutuallyAuthenticated)
4190  {
4191  throw new WebException(SR.GetString("net_webstatus_RequestCanceled"), new ProtocolViolationException(SR.GetString("net_mutualauthfailed")), WebExceptionStatus.RequestCanceled, httpResponse);
4192  }
4193  }
4194  }
4195  if (ResponseStatusCode == HttpStatusCode.BadRequest && SendChunked && HttpWriteMode != HttpWriteMode.ContentLength && ServicePoint.InternalProxyServicePoint && AllowWriteStreamBuffering)
4196  {
4197  ClearAuthenticatedConnectionResources();
4198  return true;
4199  }
4200  if (!AllowAutoRedirect || (ResponseStatusCode != HttpStatusCode.MultipleChoices && ResponseStatusCode != HttpStatusCode.MovedPermanently && ResponseStatusCode != HttpStatusCode.Found && ResponseStatusCode != HttpStatusCode.SeeOther && ResponseStatusCode != HttpStatusCode.TemporaryRedirect))
4201  {
4202  if (ResponseStatusCode > (HttpStatusCode)399)
4203  {
4204  SetExceptionIfRequired(SR.GetString("net_servererror", NetRes.GetWebStatusCodeString(ResponseStatusCode, _HttpResponse.StatusDescription)), ref e);
4205  return false;
4206  }
4207  if (AllowAutoRedirect && ResponseStatusCode > (HttpStatusCode)299)
4208  {
4209  SetExceptionIfRequired(SR.GetString("net_servererror", NetRes.GetWebStatusCodeString(ResponseStatusCode, _HttpResponse.StatusDescription)), ref e);
4210  return false;
4211  }
4212  return false;
4213  }
4214  _AutoRedirects++;
4215  if (_AutoRedirects > _MaximumAllowedRedirections)
4216  {
4217  SetExceptionIfRequired(SR.GetString("net_tooManyRedirections"), ref e);
4218  return false;
4219  }
4220  string location = _HttpResponse.Headers.Location;
4221  if (location == null)
4222  {
4223  SetExceptionIfRequired(SR.GetString("net_servererror", NetRes.GetWebStatusCodeString(ResponseStatusCode, _HttpResponse.StatusDescription)), ref e);
4224  return false;
4225  }
4226  Uri uri;
4227  try
4228  {
4229  uri = new Uri(_Uri, location);
4230  }
4231  catch (UriFormatException innerException2)
4232  {
4233  SetExceptionIfRequired(SR.GetString("net_resubmitprotofailed"), innerException2, ref e);
4234  return false;
4235  }
4236  if (IsWebSocketRequest)
4237  {
4238  if (uri.Scheme == Uri.UriSchemeWs)
4239  {
4240  UriBuilder uriBuilder = new UriBuilder(uri);
4241  uriBuilder.Scheme = Uri.UriSchemeHttp;
4242  uri = uriBuilder.Uri;
4243  }
4244  else if (uri.Scheme == Uri.UriSchemeWss)
4245  {
4246  UriBuilder uriBuilder2 = new UriBuilder(uri);
4247  uriBuilder2.Scheme = Uri.UriSchemeHttps;
4248  uri = uriBuilder2.Uri;
4249  }
4250  }
4251  if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
4252  {
4253  SetExceptionIfRequired(SR.GetString("net_resubmitprotofailed"), ref e);
4254  return false;
4255  }
4256  if (!HasRedirectPermission(uri, ref e))
4257  {
4258  return false;
4259  }
4260  Uri uri2 = _Uri;
4261  _Uri = uri;
4262  _RedirectedToDifferentHost = (Uri.Compare(_OriginUri, _Uri, UriComponents.HostAndPort, UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) != 0);
4263  if (UseCustomHost)
4264  {
4265  string hostAndPortString = GetHostAndPortString(_HostUri.Host, _HostUri.Port, addPort: true);
4266  Uri hostUri;
4267  bool flag2 = TryGetHostUri(hostAndPortString, out hostUri);
4268  if (!HasRedirectPermission(hostUri, ref e))
4269  {
4270  _Uri = uri2;
4271  return false;
4272  }
4273  _HostUri = hostUri;
4274  }
4275  if (ResponseStatusCode > (HttpStatusCode)299 && Logging.On)
4276  {
4277  Logging.PrintWarning(Logging.Web, this, "", SR.GetString("net_log_server_response_error_code", ((int)ResponseStatusCode).ToString(NumberFormatInfo.InvariantInfo)));
4278  }
4279  if (HttpWriteMode != HttpWriteMode.None)
4280  {
4281  switch (ResponseStatusCode)
4282  {
4283  case HttpStatusCode.MovedPermanently:
4284  case HttpStatusCode.Found:
4285  if (CurrentMethod.Equals(KnownHttpVerb.Post))
4286  {
4287  disableUpload = true;
4288  }
4289  break;
4290  default:
4291  disableUpload = true;
4292  break;
4293  case HttpStatusCode.TemporaryRedirect:
4294  break;
4295  }
4296  if (disableUpload)
4297  {
4298  if (!AllowWriteStreamBuffering && IsOutstandingGetRequestStream)
4299  {
4300  return false;
4301  }
4302  CurrentMethod = KnownHttpVerb.Get;
4303  ExpectContinue = false;
4304  HttpWriteMode = HttpWriteMode.None;
4305  }
4306  }
4307  ICredentials credentials = Credentials as CredentialCache;
4308  if (credentials == null)
4309  {
4310  credentials = (Credentials as SystemNetworkCredential);
4311  }
4312  if (credentials == null)
4313  {
4314  Credentials = null;
4315  }
4316  ProxyAuthenticationState.ClearAuthReq(this);
4317  ServerAuthenticationState.ClearAuthReq(this);
4318  if (_OriginUri.Scheme == Uri.UriSchemeHttps)
4319  {
4320  _HttpRequestHeaders.RemoveInternal("Referer");
4321  }
4322  }
4323  if (HttpWriteMode != HttpWriteMode.None && !AllowWriteStreamBuffering && _resendRequestContent == null && UserRetrievedWriteStream && (HttpWriteMode != HttpWriteMode.ContentLength || ContentLength != 0L))
4324  {
4325  e = new WebException(SR.GetString("net_need_writebuffering"), null, WebExceptionStatus.ProtocolError, _HttpResponse);
4326  return false;
4327  }
4328  if (!flag)
4329  {
4330  ClearAuthenticatedConnectionResources();
4331  }
4332  if (Logging.On)
4333  {
4334  Logging.PrintWarning(Logging.Web, this, "", SR.GetString("net_log_resubmitting_request"));
4335  }
4336  return true;
4337  }
4338 
4339  private bool HasRedirectPermission(Uri uri, ref Exception resultException)
4340  {
4341  try
4342  {
4343  CheckConnectPermission(uri, Async);
4344  }
4345  catch (SecurityException innerException)
4346  {
4347  resultException = new SecurityException(SR.GetString("net_redirect_perm"), new WebException(SR.GetString("net_resubmitcanceled"), innerException, WebExceptionStatus.ProtocolError, _HttpResponse));
4348  return false;
4349  }
4350  return true;
4351  }
4352 
4353  private void CheckConnectPermission(Uri uri, bool needExecutionContext)
4354  {
4355  ExecutionContext executionContext = needExecutionContext ? GetReadingContext().ContextCopy : null;
4356  CodeAccessPermission codeAccessPermission = new WebPermission(NetworkAccess.Connect, uri);
4357  if (executionContext == null)
4358  {
4359  codeAccessPermission.Demand();
4360  }
4361  else
4362  {
4363  ExecutionContext.Run(executionContext, NclUtilities.ContextRelativeDemandCallback, codeAccessPermission);
4364  }
4365  }
4366 
4367  private void ClearRequestForResubmit(bool ntlmFollowupRequest)
4368  {
4369  _HttpRequestHeaders.RemoveInternal("Host");
4370  _HttpRequestHeaders.RemoveInternal("Connection");
4371  _HttpRequestHeaders.RemoveInternal("Proxy-Connection");
4372  _HttpRequestHeaders.RemoveInternal("Content-Length");
4373  _HttpRequestHeaders.RemoveInternal("Transfer-Encoding");
4374  _HttpRequestHeaders.RemoveInternal("Expect");
4375  if (_HttpResponse != null && _HttpResponse.ResponseStream != null)
4376  {
4377  if (!_HttpResponse.KeepAlive)
4378  {
4379  (_HttpResponse.ResponseStream as ConnectStream)?.ErrorResponseNotify(isKeepAlive: false);
4380  }
4381  ICloseEx closeEx = _HttpResponse.ResponseStream as ICloseEx;
4382  if (closeEx != null)
4383  {
4384  closeEx.CloseEx(CloseExState.Silent);
4385  }
4386  else
4387  {
4388  _HttpResponse.ResponseStream.Close();
4389  }
4390  }
4391  _AbortDelegate = null;
4392  m_BodyStarted = false;
4393  HeadersCompleted = false;
4394  _WriteBufferLength = 0;
4395  m_Extra401Retry = false;
4396  HttpWebResponse httpResponse = _HttpResponse;
4397  _HttpResponse = null;
4398  m_ContinueGate.Reset();
4399  _RerequestCount++;
4400  if (!Aborted && Async)
4401  {
4402  _CoreResponse = null;
4403  }
4404  if (_SubmitWriteStream == null)
4405  {
4406  return;
4407  }
4408  if (((httpResponse != null && httpResponse.KeepAlive) || _SubmitWriteStream.IgnoreSocketErrors) && HasEntityBody)
4409  {
4411  {
4412  SetRequestContinue();
4413  }
4414  if (ntlmFollowupRequest)
4415  {
4416  NeedsToReadForResponse = !ShouldWaitFor100Continue();
4417  _SubmitWriteStream.CallDone();
4418  }
4419  else if (!AllowWriteStreamBuffering)
4420  {
4421  NeedsToReadForResponse = !ShouldWaitFor100Continue();
4422  _SubmitWriteStream.CloseInternal(internalCall: true);
4423  }
4424  else if (!Async && UserRetrievedWriteStream)
4425  {
4426  _SubmitWriteStream.CallDone();
4427  }
4428  }
4429  if ((Async || UserRetrievedWriteStream) && _OldSubmitWriteStream != null && _OldSubmitWriteStream != _SubmitWriteStream)
4430  {
4431  _SubmitWriteStream.CloseInternal(internalCall: true);
4432  }
4433  }
4434 
4435  private void FinishRequest(HttpWebResponse response, Exception errorException)
4436  {
4437  if (!_ReadAResult.InternalPeekCompleted && m_Aborted != 1 && response != null && errorException != null)
4438  {
4439  response.ResponseStream = MakeMemoryStream(response.ResponseStream);
4440  }
4441  if (errorException != null && _SubmitWriteStream != null && !_SubmitWriteStream.IsClosed)
4442  {
4443  _SubmitWriteStream.ErrorResponseNotify(_SubmitWriteStream.Connection.KeepAlive);
4444  }
4445  if (errorException == null && _HttpResponse != null && (_HttpWriteMode == HttpWriteMode.Chunked || _ContentLength > 0) && ExpectContinue && !Saw100Continue && _ServicePoint.Understands100Continue && !IsTunnelRequest && ResponseStatusCode <= (HttpStatusCode)299)
4446  {
4447  _ServicePoint.Understands100Continue = false;
4448  }
4449  }
4450 
4451  private Stream MakeMemoryStream(Stream stream)
4452  {
4453  if (stream == null || stream is SyncMemoryStream)
4454  {
4455  return stream;
4456  }
4457  SyncMemoryStream syncMemoryStream = new SyncMemoryStream(0);
4458  try
4459  {
4460  if (stream.CanRead)
4461  {
4462  byte[] array = new byte[1024];
4463  int num = 0;
4464  int num2 = (DefaultMaximumErrorResponseLength == -1) ? array.Length : (DefaultMaximumErrorResponseLength * 1024);
4465  while ((num = stream.Read(array, 0, Math.Min(array.Length, num2))) > 0)
4466  {
4467  syncMemoryStream.Write(array, 0, num);
4469  {
4470  num2 -= num;
4471  }
4472  }
4473  }
4474  syncMemoryStream.Position = 0L;
4475  return syncMemoryStream;
4476  }
4477  catch
4478  {
4479  return syncMemoryStream;
4480  }
4481  finally
4482  {
4483  try
4484  {
4485  ICloseEx closeEx = stream as ICloseEx;
4486  if (closeEx != null)
4487  {
4488  closeEx.CloseEx(CloseExState.Silent);
4489  }
4490  else
4491  {
4492  stream.Close();
4493  }
4494  }
4495  catch
4496  {
4497  }
4498  }
4499  }
4500 
4510  public void AddRange(int from, int to)
4511  {
4512  AddRange("bytes", (long)from, (long)to);
4513  }
4514 
4524  public void AddRange(long from, long to)
4525  {
4526  AddRange("bytes", from, to);
4527  }
4528 
4534  public void AddRange(int range)
4535  {
4536  AddRange("bytes", (long)range);
4537  }
4538 
4544  public void AddRange(long range)
4545  {
4546  AddRange("bytes", range);
4547  }
4548 
4561  public void AddRange(string rangeSpecifier, int from, int to)
4562  {
4563  AddRange(rangeSpecifier, (long)from, (long)to);
4564  }
4565 
4578  public void AddRange(string rangeSpecifier, long from, long to)
4579  {
4580  if (rangeSpecifier == null)
4581  {
4582  throw new ArgumentNullException("rangeSpecifier");
4583  }
4584  if (from < 0 || to < 0)
4585  {
4586  throw new ArgumentOutOfRangeException("from, to", SR.GetString("net_rangetoosmall"));
4587  }
4588  if (from > to)
4589  {
4590  throw new ArgumentOutOfRangeException("from", SR.GetString("net_fromto"));
4591  }
4592  if (!WebHeaderCollection.IsValidToken(rangeSpecifier))
4593  {
4594  throw new ArgumentException(SR.GetString("net_nottoken"), "rangeSpecifier");
4595  }
4596  if (!AddRange(rangeSpecifier, from.ToString(NumberFormatInfo.InvariantInfo), to.ToString(NumberFormatInfo.InvariantInfo)))
4597  {
4598  throw new InvalidOperationException(SR.GetString("net_rangetype"));
4599  }
4600  }
4601 
4610  public void AddRange(string rangeSpecifier, int range)
4611  {
4612  AddRange(rangeSpecifier, (long)range);
4613  }
4614 
4623  public void AddRange(string rangeSpecifier, long range)
4624  {
4625  if (rangeSpecifier == null)
4626  {
4627  throw new ArgumentNullException("rangeSpecifier");
4628  }
4629  if (!WebHeaderCollection.IsValidToken(rangeSpecifier))
4630  {
4631  throw new ArgumentException(SR.GetString("net_nottoken"), "rangeSpecifier");
4632  }
4633  if (!AddRange(rangeSpecifier, range.ToString(NumberFormatInfo.InvariantInfo), (range >= 0) ? "" : null))
4634  {
4635  throw new InvalidOperationException(SR.GetString("net_rangetype"));
4636  }
4637  }
4638 
4639  private bool AddRange(string rangeSpecifier, string from, string to)
4640  {
4641  string text = _HttpRequestHeaders["Range"];
4642  if (text == null || text.Length == 0)
4643  {
4644  text = rangeSpecifier + "=";
4645  }
4646  else
4647  {
4648  if (string.Compare(text.Substring(0, text.IndexOf('=')), rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
4649  {
4650  return false;
4651  }
4652  text = string.Empty;
4653  }
4654  text += from.ToString();
4655  if (to != null)
4656  {
4657  text = text + "-" + to;
4658  }
4659  _HttpRequestHeaders.SetAddVerified("Range", text);
4660  return true;
4661  }
4662 
4663  private static int GetStatusCode(HttpWebResponse httpWebResponse)
4664  {
4665  int result = -1;
4666  if (FrameworkEventSource.Log.IsEnabled() && httpWebResponse != null)
4667  {
4668  try
4669  {
4670  result = (int)httpWebResponse.StatusCode;
4671  return result;
4672  }
4673  catch (ObjectDisposedException)
4674  {
4675  return result;
4676  }
4677  }
4678  return result;
4679  }
4680  }
4681 }
UriKind
Defines the kinds of T:System.Uris for the M:System.Uri.IsWellFormedUriString(System....
Definition: UriKind.cs:5
Represents a character encoding.To browse the .NET Framework source code for this type,...
Definition: Encoding.cs:15
static CultureInfo InvariantCulture
Gets the T:System.Globalization.CultureInfo object that is culture-independent (invariant).
Definition: CultureInfo.cs:263
override Uri RequestUri
Gets the original Uniform Resource Identifier (URI) of the request.
override string ToString()
This method is obsolete.
The exception that is thrown when an error occurs while accessing the network through a pluggable pro...
Definition: WebException.cs:9
int Port
Gets the port number of this URI.
Definition: Uri.cs:617
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
Describes a set of security permissions applied to code. This class cannot be inherited.
unsafe string GetString(byte *bytes, int byteCount)
When overridden in a derived class, decodes a specified number of bytes starting at a specified addre...
Definition: Encoding.cs:1918
abstract int Read([In] [Out] byte[] buffer, int offset, int count)
When overridden in a derived class, reads a sequence of bytes from the current stream and advances th...
static readonly Version Version11
Defines a T:System.Version instance for HTTP 1.1.
Definition: HttpVersion.cs:10
long GetInt64(string name)
Retrieves a 64-bit signed integer value from the T:System.Runtime.Serialization.SerializationInfo sto...
bool IsDefaultPort
Gets whether the port value of the URI is the default for this scheme.
Definition: Uri.cs:447
override Stream EndGetRequestStream(IAsyncResult asyncResult)
Ends an asynchronous request for a T:System.IO.Stream object to use to write data.
UriHostNameType
Defines host name types for the M:System.Uri.CheckHostName(System.String) method.
HttpWebRequest()
Initializes a new instance of the T:System.Net.HttpWebRequest class.
DecompressionMethods
Represents the file compression and decompression encoding format to be used to compress the data rec...
override WebResponse EndGetResponse(IAsyncResult asyncResult)
Ends an asynchronous request to an Internet resource.
static readonly string UriSchemeHttp
Specifies that the URI is accessed through the Hypertext Transfer Protocol (HTTP)....
Definition: Uri.cs:154
virtual byte [] GetBytes(char[] chars)
When overridden in a derived class, encodes all the characters in the specified character array into ...
Definition: Encoding.cs:1576
unsafe override string ToString()
Converts the value of this instance to a T:System.String.
static void MemoryBarrier()
Synchronizes memory access as follows: The processor executing the current thread cannot reorder inst...
void AddRange(string rangeSpecifier, long range)
Adds a Range header to a request for a specific range from the beginning or end of the requested data...
bool SendChunked
Gets or sets a value that indicates whether to send data in segments to the Internet resource.
DateTime Date
Get or set the Date HTTP header value to use in an HTTP request.
Discovers the attributes of a method and provides access to method metadata.
Definition: MethodInfo.cs:13
virtual bool SupportsCookieContainer
Gets a value that indicates whether the request provides support for a T:System.Net....
abstract string FullName
Gets the fully qualified name of the type, including its namespace but not its assembly.
Definition: Type.cs:153
StringComparison
Specifies the culture, case, and sort rules to be used by certain overloads of the M:System....
NetworkAccess
Specifies network access permissions.
Definition: NetworkAccess.cs:5
Defines a collection that stores T:System.Security.Cryptography.X509Certificates.X509Certificate obje...
bool KeepAlive
Gets or sets a value that indicates whether to make a persistent connection to the Internet resource.
EditorBrowsableState
Specifies the browsable state of a property or method from within an editor.
Represents a missing T:System.Object. This class cannot be inherited.
Definition: Missing.cs:11
bool GetBoolean(string name)
Retrieves a Boolean value from the T:System.Runtime.Serialization.SerializationInfo store.
Makes a request to a Uniform Resource Identifier (URI). This is an abstract class.
Definition: WebRequest.cs:21
RemoteCertificateValidationCallback ServerCertificateValidationCallback
Gets or sets a callback function to validate the server certificate.
Definition: __Canon.cs:3
void AddRange(long range)
Adds a byte range header to a request for a specific range from the beginning or end of the requested...
string Scheme
Gets the scheme name for this URI.
Definition: Uri.cs:702
The exception that is thrown when the value of an argument is outside the allowable range of values a...
void AddRange(long from, long to)
Adds a byte range header to the request for a specified range.
override string ContentType
Gets or sets the value of the Content-type HTTP header.
override Stream GetRequestStream()
Gets a T:System.IO.Stream object to use to write request data.
delegate void AsyncCallback(IAsyncResult ar)
References a method to be called when a corresponding asynchronous operation completes.
override string ConnectionGroupName
Gets or sets the name of the connection group for the request.
override bool PreAuthenticate
Gets or sets a value that indicates whether to send an Authorization header with the request.
static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object state)
Queues the specified delegate to the thread pool, but does not propagate the calling stack to the wor...
Definition: ThreadPool.cs:312
string PathAndQuery
Gets the P:System.Uri.AbsolutePath and P:System.Uri.Query properties separated by a question mark (?...
Definition: Uri.cs:507
string Connection
Gets or sets the value of the Connection HTTP header.
Represents an instant in time, typically expressed as a date and time of day. To browse the ....
Definition: DateTime.cs:13
delegate bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
Verifies the remote Secure Sockets Layer (SSL) certificate used for authentication.
Defines the HTTP version numbers that are supported by the T:System.Net.HttpWebRequest and T:System....
Definition: HttpVersion.cs:4
HttpStatusCode
Contains the values of status codes defined for HTTP.
override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
Begins an asynchronous request for a T:System.IO.Stream object to use to write data.
Describes the source and destination of a given serialized stream, and provides an additional caller-...
static int DefaultMaximumResponseHeadersLength
Gets or sets the default for the P:System.Net.HttpWebRequest.MaximumResponseHeadersLength property.
void AddRange(int range)
Adds a byte range header to a request for a specific range from the beginning or end of the requested...
void AddRange(string rangeSpecifier, int range)
Adds a Range header to a request for a specific range from the beginning or end of the requested data...
A type representing a date and time value.
UriComponents
Specifies the parts of a T:System.Uri.
Definition: UriComponents.cs:6
static int Exchange(ref int location1, int value)
Sets a 32-bit signed integer to a specified value and returns the original value, as an atomic operat...
static Encoding ASCII
Gets an encoding for the ASCII (7-bit) character set.
Definition: Encoding.cs:920
WebResponse Response
Gets the response that the remote host returned.
Definition: WebException.cs:34
Contains protocol headers associated with a request or response.
override WebResponse GetResponse()
Returns a response from an Internet resource.
HttpContinueDelegate ContinueDelegate
Gets or sets the delegate method called when an HTTP 100-continue response is received from the Inter...
override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
Begins an asynchronous request to an Internet resource.
int MaximumResponseHeadersLength
Gets or sets the maximum allowed length of the response headers.
override long ContentLength
Gets or sets the Content-length HTTP header.
abstract bool CanRead
When overridden in a derived class, gets a value indicating whether the current stream supports readi...
Definition: Stream.cs:577
HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext)
Initializes a new instance of the T:System.Net.HttpWebRequest class from the specified instances of t...
int ReadWriteTimeout
Gets or sets a time-out in milliseconds when writing to or reading from a stream.
SecurityAction
Specifies the security actions that can be performed using declarative security.
string MediaType
Gets or sets the media type of the request.
virtual void Close()
Closes the current stream and releases any resources (such as sockets and file handles) associated wi...
Definition: Stream.cs:855
DateTime IfModifiedSince
Gets or sets the value of the If-Modified-Since HTTP header.
Provides a response from a Uniform Resource Identifier (URI). This is an abstract class.
Definition: WebResponse.cs:10
Represents the status of an asynchronous operation.
Definition: IAsyncResult.cs:9
Manages the execution context for the current thread. This class cannot be inherited.
StringBuilder Append(char value, int repeatCount)
Appends a specified number of copies of the string representation of a Unicode character to this inst...
void AddValue(string name, object value, Type type)
Adds a value into the T:System.Runtime.Serialization.SerializationInfo store, where value is associa...
virtual bool AllowAutoRedirect
Gets or sets a value that indicates whether the request should follow redirection responses.
The T:System.Net.TransportContext class provides additional context about the underlying transport la...
bool Expect100Continue
Gets or sets a T:System.Boolean value that determines whether 100-Continue behavior is used.
Version ProtocolVersion
Gets or sets the version of HTTP to use for the request.
The exception that is thrown when an error is made while using a network protocol.
Throws an exception for a Win32 error code.
static readonly Version Version10
Defines a T:System.Version instance for HTTP 1.0.
Definition: HttpVersion.cs:7
DecompressionMethods AutomaticDecompression
Gets or sets the type of decompression that is used.
Provides storage for multiple credentials.
static int CompareExchange(ref int location1, int value, int comparand)
Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.
static readonly DBNull Value
Represents the sole instance of the T:System.DBNull class.
Definition: DBNull.cs:13
override WebHeaderCollection Headers
Gets the headers that are associated with this response from the server.
virtual bool HaveResponse
Gets a value that indicates whether a response has been received from an Internet resource.
static int Increment(ref int location)
Increments a specified variable and stores the result, as an atomic operation.
Definition: Interlocked.cs:18
static ICredentials DefaultCredentials
Gets the system credentials of the application.
A database null (column) value.
Defines the underlying structure of all code access permissions.
override IWebProxy Proxy
Gets or sets proxy information for the request.
Provides the base authentication interface for retrieving credentials for Web client authentication.
Definition: ICredentials.cs:5
static RequestCachePolicy DefaultCachePolicy
Gets or sets the default cache policy for this request.
Definition: WebRequest.cs:170
int MaximumAutomaticRedirections
Gets or sets the maximum number of redirects that the request follows.
static void Run(ExecutionContext executionContext, ContextCallback callback, object state)
Runs a method in a specified execution context on the current thread.
string Accept
Gets or sets the value of the Accept HTTP header.
Represents the version number of an assembly, operating system, or the common language runtime....
Definition: Version.cs:11
Type DeclaringType
Provides COM objects with version-independent access to the P:System.Reflection.MemberInfo....
Definition: _MethodInfo.cs:31
WebRequest()
Initializes a new instance of the T:System.Net.WebRequest class.
Definition: WebRequest.cs:673
static int DefaultMaximumErrorResponseLength
Gets or sets the default maximum length of an HTTP error response.
virtual HttpStatusCode StatusCode
Gets the status of the response.
Provides an HTTP-specific implementation of the T:System.Net.WebResponse class.
string GetComponents(UriComponents components, UriFormat format)
Gets the specified components of the current instance using the specified escaping for special charac...
Definition: Uri.cs:4874
void AddRange(string rangeSpecifier, long from, long to)
Adds a range header to a request for a specified range.
override string Get(string name)
Gets the value of a particular header in the collection, specified by the name of the header.
string Expect
Gets or sets the value of the Expect HTTP header.
ServicePoint ServicePoint
Gets the service point to use for the request.
virtual string Message
Gets a message that describes the current exception.
Definition: Exception.cs:95
Defines an application's caching requirements for resources obtained by using T:System....
Contains constants that specify infinite time-out intervals. This class cannot be inherited.
Definition: Timeout.cs:8
virtual string StatusDescription
Gets the status description returned with the response.
Stores all the data needed to serialize or deserialize an object. This class cannot be inherited.
Represents a mutable string of characters. This class cannot be inherited.To browse the ....
static void RevertAssert()
Causes any previous M:System.Security.CodeAccessPermission.Assert for the current frame to be removed...
Stream GetRequestStream(out TransportContext context)
Gets a T:System.IO.Stream object to use to write request data and outputs the T:System....
int ContinueTimeout
Gets or sets a timeout, in milliseconds, to wait until the 100-Continue is received from the server.
WebExceptionStatus
Defines status codes for the T:System.Net.WebException class.
Exception()
Initializes a new instance of the T:System.Exception class.
Definition: Exception.cs:286
NetworkCredential GetCredential(Uri uri, string authType)
Returns a T:System.Net.NetworkCredential object that is associated with the specified URI,...
The exception that is thrown when one of the arguments provided to a method is not valid.
void Demand()
Forces a T:System.Security.SecurityException at run time if all callers higher in the call stack have...
Stream EndGetRequestStream(IAsyncResult asyncResult, out TransportContext context)
Ends an asynchronous request for a T:System.IO.Stream object to use to write data and outputs the T:S...
int Count
Gets the number of elements contained in the T:System.Collections.CollectionBase instance....
static readonly Missing Value
Represents the sole instance of the T:System.Reflection.Missing class.
Definition: Missing.cs:15
virtual bool AllowReadStreamBuffering
Gets or sets a value that indicates whether to buffer the received from the Internet resource.
override bool? UseDefaultCredentials
Gets or sets a T:System.Boolean value that controls whether default credentials are sent with request...
UriFormat
Controls how URI information is escaped.
Definition: UriFormat.cs:5
Allows an object to control its own serialization and deserialization.
Definition: ISerializable.cs:8
Uri Address
Gets the Uniform Resource Identifier (URI) of the Internet resource that actually responds to the req...
PermissionState
Specifies whether a permission should have all or no access to resources at creation.
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
Definition: Exception.cs:22
string Host
Get or set the Host header value to use in an HTTP request independent from the request URI.
virtual bool AllowWriteStreamBuffering
Gets or sets a value that indicates whether to buffer the data sent to the Internet resource.
void AddRange(string rangeSpecifier, int from, int to)
Adds a range header to a request for a specified range.
bool UnsafeAuthenticatedConnectionSharing
Gets or sets a value that indicates whether to allow high-speed NTLM-authenticated connection sharing...
override int GetHashCode()
Builds a hash value based on all values contained in the current T:System.Security....
string GetString(string name)
Retrieves a T:System.String value from the T:System.Runtime.Serialization.SerializationInfo store.
bool CloseConnectionGroup(string connectionGroupName)
Removes the specified connection group from this T:System.Net.ServicePoint object.
object GetValue(string name, Type type)
Retrieves a value from the T:System.Runtime.Serialization.SerializationInfo store.
override ICredentials Credentials
Gets or sets authentication information for the request.
bool Pipelined
Gets or sets a value that indicates whether to pipeline the request to the Internet resource.
Specifies that the class can be serialized.
void AddRange(int from, int to)
Adds a byte range header to the request for a specified range.
string TransferEncoding
Gets or sets the value of the Transfer-encoding HTTP header.
ICredentials Credentials
The credentials to submit to the proxy server for authentication.
Definition: IWebProxy.cs:11
The exception that is thrown when a method call is invalid for the object's current state.
override WebHeaderCollection Headers
Specifies a collection of the name/value pairs that make up the HTTP headers.
int GetInt32(string name)
Retrieves a 32-bit signed integer value from the T:System.Runtime.Serialization.SerializationInfo sto...
override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
Populates a T:System.Runtime.Serialization.SerializationInfo with the data required to serialize the ...
Provides the base interface for implementation of proxy access for the T:System.Net....
Definition: IWebProxy.cs:5
void Assert()
Declares that the calling code can access the resource protected by a permission demand through the c...
Provides credentials for password-based authentication schemes such as basic, digest,...
delegate void WaitCallback(object state)
Represents a callback method to be executed by a thread pool thread.
Provides information about a specific culture (called a locale for unmanaged code development)....
Definition: CultureInfo.cs:16
override string Method
Gets or sets the method for the request.
SecurityPermissionFlag
Specifies access flags for the security permission object.
Provides an object representation of a uniform resource identifier (URI) and easy access to the parts...
Definition: Uri.cs:19
Provides an HTTP-specific implementation of the T:System.Net.WebRequest class.
override void Abort()
Cancels a request to an Internet resource.
Controls access to non-public types and members through the N:System.Reflection APIs....
static new RequestCachePolicy DefaultCachePolicy
Gets or sets the default cache policy for this request.
void GetObjectData(SerializationInfo info, StreamingContext context)
Populates a T:System.Runtime.Serialization.SerializationInfo with the data needed to serialize the ta...
string Host
Gets the host component of this instance.
Definition: Uri.cs:587
Provides atomic operations for variables that are shared by multiple threads.
Definition: Interlocked.cs:10
X509CertificateCollection ClientCertificates
Gets or sets the collection of security certificates that are associated with this request.
The default setting for this enumeration, which is currently F:System.GCCollectionMode....
The exception that is thrown when a security error is detected.
string Referer
Gets or sets the value of the Referer HTTP header.
HttpResponseHeader
The HTTP headers that can be specified in a server response.
static NumberFormatInfo InvariantInfo
Gets a read-only T:System.Globalization.NumberFormatInfo object that is culture-independent (invarian...
Provides connection management for HTTP connections.
Definition: ServicePoint.cs:16
delegate void HttpContinueDelegate(int StatusCode, WebHeaderCollection httpHeaders)
Represents the method that notifies callers when a continue response is received by the client.
Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I...
Definition: ThreadPool.cs:14
Represents a nonexistent value. This class cannot be inherited.
Definition: DBNull.cs:10
AuthenticationLevel
Specifies client requirements for authentication and impersonation when using the T:System....
static void SpinWait(int iterations)
Causes a thread to wait the number of times defined by the iterations parameter.
Definition: Thread.cs:779
Provides culture-specific information for formatting and parsing numeric values.
Provides a generic view of a sequence of bytes. This is an abstract class.To browse the ....
Definition: Stream.cs:16
string UserAgent
Gets or sets the value of the User-agent HTTP header.
Creates and controls a thread, sets its priority, and gets its status.
Definition: Thread.cs:18