-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathHttpContext.cs
2349 lines (1987 loc) · 93.4 KB
/
HttpContext.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// <copyright file="HttpContext.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* HttpContext class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Remoting.Messaging;
using System.Security.Permissions;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Caching;
using System.Web.Compilation;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Instrumentation;
using System.Web.Management;
using System.Web.Profile;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.Util;
using System.Web.WebSockets;
/// <devdoc>
/// <para>Encapsulates
/// all HTTP-specific
/// context used by the HTTP server to process Web requests.</para>
/// <para>System.Web.IHttpModules and System.Web.IHttpHandler instances are provided a
/// reference to an appropriate HttpContext object. For example
/// the Request and Response
/// objects.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Usage", "CA2302:FlagServiceProviders", Justification = "The service provider implementation is only for specific types which are not com interop types.")]
public sealed class HttpContext : IServiceProvider, IPrincipalContainer
{
internal static readonly Assembly SystemWebAssembly = typeof(HttpContext).Assembly;
private static volatile bool s_eurlSet;
private static string s_eurl;
private IHttpAsyncHandler _asyncAppHandler; // application as handler (not always HttpApplication)
private AsyncPreloadModeFlags _asyncPreloadModeFlags;
private bool _asyncPreloadModeFlagsSet;
private HttpApplication _appInstance;
private IHttpHandler _handler;
[DoNotReset]
private HttpRequest _request;
private HttpResponse _response;
private HttpServerUtility _server;
private Stack _traceContextStack;
private TraceContext _topTraceContext;
[DoNotReset]
private Hashtable _items;
private ArrayList _errors;
private Exception _tempError;
private bool _errorCleared;
[DoNotReset]
private IPrincipalContainer _principalContainer;
[DoNotReset]
internal ProfileBase _Profile;
[DoNotReset]
private DateTime _utcTimestamp;
[DoNotReset]
private HttpWorkerRequest _wr;
private VirtualPath _configurationPath;
internal bool _skipAuthorization;
[DoNotReset]
private CultureInfo _dynamicCulture;
[DoNotReset]
private CultureInfo _dynamicUICulture;
private int _serverExecuteDepth;
private Stack _handlerStack;
private bool _preventPostback;
private bool _runtimeErrorReported;
private PageInstrumentationService _pageInstrumentationService = null;
private ReadOnlyCollection<string> _webSocketRequestedProtocols;
// timeout support
[DoNotReset]
private CancellationTokenHelper _timeoutCancellationTokenHelper; // used for TimedOutToken
private long _timeoutStartTimeUtcTicks = -1; // should always be accessed atomically; -1 means uninitialized
private long _timeoutTicks = -1; // should always be accessed atomically; -1 means uninitialized
private int _timeoutState; // 0=non-cancelable, 1=cancelable, -1=canceled
private DoubleLink _timeoutLink; // link in the timeout's manager list
private bool _threadAbortOnTimeout = true; // whether we should Thread.Abort() this thread when it times out
private Thread _thread;
// cached configuration
private CachedPathData _configurationPathData; // Cached data if _configurationPath != null
private CachedPathData _filePathData; // Cached data of the file being requested
// Sql Cache Dependency
private string _sqlDependencyCookie;
// Session State
volatile SessionStateModule _sessionStateModule;
volatile bool _delayedSessionState; // Delayed session state item
// non-compiled pages
private TemplateControl _templateControl;
// integrated pipeline state
// For the virtual Disposing / Disposed events
private SubscriptionQueue<Action<HttpContext>> _requestCompletedQueue;
[DoNotReset]
private SubscriptionQueue<IDisposable> _pipelineCompletedQueue;
// keep synchronized with mgdhandler.hxx
private const int FLAG_NONE = 0x0;
private const int FLAG_CHANGE_IN_SERVER_VARIABLES = 0x1;
private const int FLAG_CHANGE_IN_REQUEST_HEADERS = 0x2;
private const int FLAG_CHANGE_IN_RESPONSE_HEADERS = 0x4;
private const int FLAG_CHANGE_IN_USER_OBJECT = 0x8;
private const int FLAG_SEND_RESPONSE_HEADERS = 0x10;
private const int FLAG_RESPONSE_HEADERS_SENT = 0x20;
internal const int FLAG_ETW_PROVIDER_ENABLED = 0x40;
private const int FLAG_CHANGE_IN_RESPONSE_STATUS = 0x80;
private volatile NotificationContext _notificationContext;
private bool _isAppInitialized;
[DoNotReset]
private bool _isIntegratedPipeline;
private bool _finishPipelineRequestCalled;
[DoNotReset]
private bool _impersonationEnabled;
internal bool HideRequestResponse;
internal volatile bool InIndicateCompletion;
internal volatile ThreadContext IndicateCompletionContext = null;
internal volatile Thread ThreadInsideIndicateCompletion = null;
// This field is a surrogate for the HttpContext object itself. Our HostExecutionContextManager
// shouldn't capture a reference to the HttpContext itself since these references could be long-lived,
// e.g. if they're captured by a call to ThreadPool.QueueUserWorkItem or a Timer. This would cause the
// associated HttpContext object graph to be long-lived, which would negatively affect performance.
// Instead we capture a reference to this 'Id' object, which allows the HostExecutionContextManager
// to compare the original captured HttpContext with the current HttpContext without actually
// holding on to the original HttpContext instance.
[DoNotReset]
internal readonly object ThreadContextId = new object();
// synchronization context (for EAP / TAP models)
private AspNetSynchronizationContextBase _syncContext;
// This field doesn't need to be volatile since it will only ever be written to by a single thread, and when that thread
// later reads the field it will be guaranteed non-null. We don't care what other threads see, since it will never be
// equal to Thread.CurrentThread for them regardless of whether those threads are seeing the latest value of this field.
// This field should not be marked [DoNotReset] since we want it to be cleared when WebSocket processing begins.
internal Thread _threadWhichStartedWebSocketTransition;
// WebSocket state
[DoNotReset]
private WebSocketTransitionState _webSocketTransitionState; // see comments in WebSocketTransitionState.cs for detailed info on this enum
[DoNotReset]
private string _webSocketNegotiatedProtocol;
// see comments on WebSocketInitStatus for what all of these codes mean
private WebSocketInitStatus GetWebSocketInitStatus() {
IIS7WorkerRequest iis7wr =_wr as IIS7WorkerRequest;
if (iis7wr == null) {
return WebSocketInitStatus.RequiresIntegratedMode;
}
if (CurrentNotification <= RequestNotification.BeginRequest) {
return WebSocketInitStatus.CannotCallFromBeginRequest;
}
if (!iis7wr.IsWebSocketRequest()) {
if (iis7wr.IsWebSocketModuleActive()) {
return WebSocketInitStatus.NotAWebSocketRequest;
}
else {
return WebSocketInitStatus.NativeModuleNotEnabled;
}
}
if (iis7wr.GetIsChildRequest()) {
return WebSocketInitStatus.CurrentRequestIsChildRequest;
}
return WebSocketInitStatus.Success;
}
// Returns true if the request contained the initial WebSocket handshake
// and IIS's WebSocket module is active.
public bool IsWebSocketRequest {
get {
// If AcceptWebSocketRequest has already been called and run to completion, then this
// is obviously a WebSocket request and we can skip further checks (which might throw).
if (IsWebSocketRequestUpgrading) {
return true;
}
switch (GetWebSocketInitStatus()) {
case WebSocketInitStatus.RequiresIntegratedMode:
throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
case WebSocketInitStatus.CannotCallFromBeginRequest:
throw new InvalidOperationException(SR.GetString(SR.WebSockets_CannotBeCalledDuringBeginRequest));
case WebSocketInitStatus.Success:
return true;
default:
return false;
}
}
}
// While unwinding an HTTP request this indicates if the developer
// told ASP.NET that they wanted to transition to a websocket request
public bool IsWebSocketRequestUpgrading {
get { return (WebSocketTransitionState >= WebSocketTransitionState.AcceptWebSocketRequestCalled); }
}
internal bool HasWebSocketRequestTransitionStarted {
get { return WebSocketTransitionState >= WebSocketTransitionState.TransitionStarted; }
}
internal bool HasWebSocketRequestTransitionCompleted {
get { return WebSocketTransitionState >= WebSocketTransitionState.TransitionCompleted; }
}
internal WebSocketTransitionState WebSocketTransitionState {
get { return _webSocketTransitionState; }
private set { _webSocketTransitionState = value; }
}
// Returns the ordered list of protocols requested by the client,
// or an empty collection if this wasn't a WebSocket request or there was no list present.
public IList<string> WebSocketRequestedProtocols {
get {
if (IsWebSocketRequest) {
if (_webSocketRequestedProtocols == null) {
string rawHeaderValue = _wr.GetUnknownRequestHeader("Sec-WebSocket-Protocol");
IList<string> requestedProtocols = SubProtocolUtil.ParseHeader(rawHeaderValue); // checks for invalid values
_webSocketRequestedProtocols = new ReadOnlyCollection<string>(requestedProtocols ?? new string[0]);
}
return _webSocketRequestedProtocols;
}
else {
// not a WebSocket request
return null;
}
}
}
// Returns the negotiated protocol (sent from the server to the client) for a
// WebSocket request.
public string WebSocketNegotiatedProtocol {
get { return _webSocketNegotiatedProtocol; }
}
public void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc) {
AcceptWebSocketRequest(userFunc, null);
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This is a safe critical method.")]
public void AcceptWebSocketRequest(Func<AspNetWebSocketContext, Task> userFunc, AspNetWebSocketOptions options) {
// Begin argument & state checking
// We throw different error codes depending on the check that failed. Things that are
// server configuration errors (WebSockets not enabled) or developer errors (called this
// method with bad parameters) result in an appropriate exception type. Things that are
// remote errors (e.g. bad parameters from the client) result in an HTTP 4xx.
if (userFunc == null) {
throw new ArgumentNullException("userFunc");
}
if (IsWebSocketRequestUpgrading) {
// this method cannot be called multiple times
throw new InvalidOperationException(SR.GetString(SR.WebSockets_AcceptWebSocketRequestCanOnlyBeCalledOnce));
}
// DevDiv #384514: Task<T> doesn't work correctly using the legacy SynchronizationContext setting. Since
// WebSockets operation requires correct Task<T> behavior, we should forbid using the feature when legacy
// mode is enabled.
SynchronizationContextUtil.ValidateModeForWebSockets();
switch (GetWebSocketInitStatus()) {
case WebSocketInitStatus.RequiresIntegratedMode:
throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
case WebSocketInitStatus.CannotCallFromBeginRequest:
throw new InvalidOperationException(SR.GetString(SR.WebSockets_CannotBeCalledDuringBeginRequest));
case WebSocketInitStatus.NativeModuleNotEnabled:
throw new PlatformNotSupportedException(SR.GetString(SR.WebSockets_WebSocketModuleNotEnabled));
case WebSocketInitStatus.NotAWebSocketRequest:
throw new HttpException((int)HttpStatusCode.BadRequest, SR.GetString(SR.WebSockets_NotAWebSocketRequest));
case WebSocketInitStatus.CurrentRequestIsChildRequest:
throw new InvalidOperationException(SR.GetString(SR.WebSockets_CannotBeCalledDuringChildExecute));
case WebSocketInitStatus.Success:
break;
default:
// fallback error message - not a WebSocket request
throw new HttpException(SR.GetString(SR.WebSockets_UnknownErrorWhileAccepting));
}
if (CurrentNotification > RequestNotification.ExecuteRequestHandler) {
// it is too late to call this method
throw new InvalidOperationException(SR.GetString(SR.WebSockets_CannotBeCalledAfterHandlerExecute));
}
// End argument & state checking
IIS7WorkerRequest wr = (IIS7WorkerRequest)_wr;
// Begin options checking and parsing
if (options != null && options.RequireSameOrigin) {
if (!WebSocketUtil.IsSameOriginRequest(wr)) {
// use Forbidden (HTTP 403) since it's not an authentication error; it's a usage error
throw new HttpException((int)HttpStatusCode.Forbidden, SR.GetString(SR.WebSockets_OriginCheckFailed));
}
}
string subprotocol = null;
if (options != null && !String.IsNullOrEmpty(options.SubProtocol)) {
// AspNetWebSocketOptions.set_SubProtocol() already checked that the provided value is valid
subprotocol = options.SubProtocol;
}
if (subprotocol != null) {
IList<string> incomingProtocols = WebSocketRequestedProtocols;
if (incomingProtocols == null || !incomingProtocols.Contains(subprotocol, StringComparer.Ordinal)) {
// The caller requested a subprotocol that wasn't in the list of accepted protocols coming from the client.
// This is disallowed by the WebSockets protocol spec, Sec. 5.2.2 (#2).
throw new ArgumentException(SR.GetString(SR.WebSockets_SubProtocolCannotBeNegotiated, subprotocol), "options");
}
}
// End options checking and parsing
wr.AcceptWebSocket();
// transition: Inactive -> AcceptWebSocketRequestCalled
TransitionToWebSocketState(WebSocketTransitionState.AcceptWebSocketRequestCalled);
Response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // 101
if (subprotocol != null) {
Response.AppendHeader("Sec-WebSocket-Protocol", subprotocol);
_webSocketNegotiatedProtocol = subprotocol;
}
RootedObjects.WebSocketPipeline = new WebSocketPipeline(RootedObjects, this, userFunc, subprotocol);
}
internal void TransitionToWebSocketState(WebSocketTransitionState newState) {
// Make sure the state transition is happening in the correct order
#if DBG
WebSocketTransitionState expectedOldState = checked(newState - 1);
Debug.Assert(WebSocketTransitionState == expectedOldState, String.Format(CultureInfo.InvariantCulture, "Expected WebSocketTransitionState to be '{0}', but it was '{1}'.", expectedOldState, WebSocketTransitionState));
#endif
WebSocketTransitionState = newState;
if (newState == Web.WebSocketTransitionState.TransitionStarted) {
_threadWhichStartedWebSocketTransition = Thread.CurrentThread;
}
}
internal bool DidCurrentThreadStartWebSocketTransition {
get {
return _threadWhichStartedWebSocketTransition == Thread.CurrentThread;
}
}
// helper that throws an exception if we have transitioned the current request to a WebSocket request
internal void EnsureHasNotTransitionedToWebSocket() {
if (HasWebSocketRequestTransitionCompleted) {
throw new NotSupportedException(SR.GetString(SR.WebSockets_MethodNotAvailableDuringWebSocketProcessing));
}
}
internal bool FirstRequest {get; set;}
// session state support
private bool _requiresSessionStateFromHandler;
internal bool RequiresSessionState {
get {
switch (SessionStateBehavior) {
case SessionStateBehavior.Required:
case SessionStateBehavior.ReadOnly:
return true;
case SessionStateBehavior.Disabled:
return false;
case SessionStateBehavior.Default:
default:
return _requiresSessionStateFromHandler;
}
}
}
private bool _readOnlySessionStateFromHandler;
internal bool ReadOnlySessionState {
get {
switch (SessionStateBehavior) {
case SessionStateBehavior.ReadOnly:
return true;
case SessionStateBehavior.Required:
case SessionStateBehavior.Disabled:
return false;
case SessionStateBehavior.Default:
default:
return _readOnlySessionStateFromHandler;
}
}
}
internal bool InAspCompatMode;
private IHttpHandler _remapHandler = null;
/// <include file='doc\HttpContext.uex' path='docs/doc[@for="HttpContext.HttpContext"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the HttpContext class.
/// </para>
/// </devdoc>
public HttpContext(HttpRequest request, HttpResponse response) {
Init(request, response);
request.Context = this;
response.Context = this;
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the HttpContext class.
/// </para>
/// </devdoc>
public HttpContext(HttpWorkerRequest wr) {
_wr = wr;
Init(new HttpRequest(wr, this), new HttpResponse(wr, this));
_response.InitResponseWriter();
}
// ctor used in HttpRuntime
internal HttpContext(HttpWorkerRequest wr, bool initResponseWriter) {
_wr = wr;
Init(new HttpRequest(wr, this), new HttpResponse(wr, this));
if (initResponseWriter)
_response.InitResponseWriter();
PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_EXECUTING);
}
private void Init(HttpRequest request, HttpResponse response) {
_request = request;
_response = response;
_utcTimestamp = DateTime.UtcNow;
_principalContainer = this;
if (_wr is IIS7WorkerRequest) {
_isIntegratedPipeline = true;
}
if (!(_wr is System.Web.SessionState.StateHttpWorkerRequest))
CookielessHelper.RemoveCookielessValuesFromPath(); // This ensures that the cookieless-helper is initialized and
// rewrites the path if the URI contains cookieless form-auth ticket, session-id, etc.
Profiler p = HttpRuntime.Profile;
if (p != null && p.IsEnabled)
_topTraceContext = new TraceContext(this);
// rewrite path in order to remove "/eurl.axd/guid", if it was
// added to the URL by aspnet_filter.dll.
string eurl = GetEurl();
if (!String.IsNullOrEmpty(eurl)) {
string path = request.Path;
int idxStartEurl = path.Length - eurl.Length;
bool hasTrailingSlash = (path[path.Length - 1] == '/');
if (hasTrailingSlash) {
idxStartEurl--;
}
if (idxStartEurl >= 0
&& StringUtil.Equals(path, idxStartEurl, eurl, 0, eurl.Length)) {
// restore original URL
int originalUrlLen = idxStartEurl;
if (hasTrailingSlash) {
originalUrlLen++;
}
string originalUrl = path.Substring(0, originalUrlLen);
// Dev10 835901: We don't call HttpContext.RewritePath(path) because the
// original path may contain '?' encoded as %3F, and RewritePath
// would interpret what follows as the query string. So instead, we
// clear ConfigurationPath and call InternalRewritePath directly.
ConfigurationPath = null;
Request.InternalRewritePath(VirtualPath.Create(originalUrl), null, true);
}
}
}
// We have a feature that directs extensionless URLs
// into managed code by appending "/eurl.axd/guid" to the path. On IIS 6.0,
// we restore the URL as soon as we get into managed code. Here we get the
// actual value of "/eurl.axd/guid" and remember it.
private string GetEurl() {
// only used on IIS 6.0
if (!(_wr is ISAPIWorkerRequestInProcForIIS6)
|| (_wr is ISAPIWorkerRequestInProcForIIS7)) {
return null;
}
string eurl = s_eurl;
if (eurl == null && !s_eurlSet) {
try {
IntPtr pBuffer = UnsafeNativeMethods.GetExtensionlessUrlAppendage();
if (pBuffer != IntPtr.Zero) {
eurl = StringUtil.StringFromWCharPtr(pBuffer, UnsafeNativeMethods.lstrlenW(pBuffer));
}
}
catch {} // ignore all exceptions
s_eurl = eurl;
s_eurlSet = true;
}
return eurl;
}
// Current HttpContext off the call context
#if DBG
internal static void SetDebugAssertOnAccessToCurrent(bool doAssert) {
if (doAssert) {
CallContext.SetData("__ContextAssert", String.Empty);
}
else {
CallContext.SetData("__ContextAssert", null);
}
}
private static bool NeedDebugAssertOnAccessToCurrent {
get {
return (CallContext.GetData("__ContextAssert") != null);
}
}
#endif
/// <devdoc>
/// <para>Returns the current HttpContext object.</para>
/// </devdoc>
public static HttpContext Current {
get {
#if DBG
if (NeedDebugAssertOnAccessToCurrent) {
Debug.Assert(ContextBase.Current != null);
}
#endif
return ContextBase.Current as HttpContext;
}
set {
ContextBase.Current = value;
}
}
//
// Root / unroot for the duration of async operation
// These are only used for the classic pipeline. The integrated pipeline uses a different rooting mechanism.
//
private IntPtr _rootedPtr;
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This is a safe critical method.")]
internal void Root() {
_rootedPtr = GCUtil.RootObject(this);
}
internal void Unroot() {
GCUtil.UnrootObject(_rootedPtr);
_rootedPtr = IntPtr.Zero;
}
internal void FinishPipelineRequest() {
if (!_finishPipelineRequestCalled) {
_finishPipelineRequestCalled = true;
HttpRuntime.FinishPipelineRequest(this);
}
}
// This is a virtual event which occurs when the HTTP part of this request is winding down, e.g. after EndRequest
// but before the WebSockets pipeline kicks in. The HttpContext is still available for inspection and is provided
// as a parameter to the supplied callback.
[SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate", Justification = @"The normal event pattern doesn't work between HttpContext and HttpContextBase since the signatures differ.")]
public ISubscriptionToken AddOnRequestCompleted(Action<HttpContext> callback) {
if (callback == null) {
throw new ArgumentNullException("callback");
}
return _requestCompletedQueue.Enqueue(callback);
}
internal void RaiseOnRequestCompleted() {
// The callbacks really shouldn't throw exceptions, but we have a catch block just in case.
// Since there's nobody else that can listen for these errors (the request is unwinding and
// user code will no longer run), we'll just log the error.
try {
_requestCompletedQueue.FireAndComplete(action => action(this));
}
catch (Exception e) {
WebBaseEvent.RaiseRuntimeError(e, this);
}
finally {
// Dispose of TimedOutToken so that nobody tries using it after this point.
DisposeTimedOutToken();
}
}
// Allows an object's Dispose() method to be called when the pipeline part of this request is completed, e.g.
// after both the HTTP part and the WebSockets loop have completed. The HttpContext is not available for
// inspection, and HttpContext.Current will be null.
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This is a safe critical method.")]
public ISubscriptionToken DisposeOnPipelineCompleted(IDisposable target) {
if (target == null) {
throw new ArgumentNullException("target");
}
if (RootedObjects != null) {
// integrated pipeline
return RootedObjects.DisposeOnPipelineCompleted(target);
}
else {
// classic pipeline
return _pipelineCompletedQueue.Enqueue(target);
}
}
internal void RaiseOnPipelineCompleted() {
// The callbacks really shouldn't throw exceptions, but we have a catch block just in case.
// Since there's nobody else that can listen for these errors (the request is unwinding and
// user code will no longer run), we'll just log the error.
try {
_pipelineCompletedQueue.FireAndComplete(disposable => disposable.Dispose());
}
catch (Exception e) {
WebBaseEvent.RaiseRuntimeError(e, null);
}
}
internal void ValidatePath() {
CachedPathData pathData = GetConfigurationPathData();
pathData.ValidatePath(_request.PhysicalPathInternal);
}
// IServiceProvider implementation
/// <internalonly/>
Object IServiceProvider.GetService(Type service) {
Object obj;
if (service == typeof(HttpWorkerRequest)) {
InternalSecurityPermissions.UnmanagedCode.Demand();
obj = _wr;
}
else if (service == typeof(HttpRequest))
obj = Request;
else if (service == typeof(HttpResponse))
obj = Response;
else if (service == typeof(HttpApplication))
obj = ApplicationInstance;
else if (service == typeof(HttpApplicationState))
obj = Application;
else if (service == typeof(HttpSessionState))
obj = Session;
else if (service == typeof(HttpServerUtility))
obj = Server;
else
obj = null;
return obj;
}
//
// Async app handler is remembered for the duration of execution of the
// request when application happens to be IHttpAsyncHandler. It is needed
// for HttpRuntime to remember the object on which to call OnEndRequest.
//
// The assumption is that application is a IHttpAsyncHandler, not always
// HttpApplication.
//
internal IHttpAsyncHandler AsyncAppHandler {
get { return _asyncAppHandler; }
set { _asyncAppHandler = value; }
}
public AsyncPreloadModeFlags AsyncPreloadMode {
get {
if (!_asyncPreloadModeFlagsSet) {
_asyncPreloadModeFlags = RuntimeConfig.GetConfig(this).HttpRuntime.AsyncPreloadMode;
_asyncPreloadModeFlagsSet = true;
}
return _asyncPreloadModeFlags;
}
set {
_asyncPreloadModeFlags = value;
_asyncPreloadModeFlagsSet = true;
}
}
// If this flag is not set, the AspNetSynchronizationContext associated with this request will throw
// exceptions when it detects the application misusing the async API. This can occur if somebody
// tries to call SynchronizationContext.Post / OperationStarted / etc. during a part of the
// pipeline where we weren't expecting asynchronous work to take place, if there is still
// outstanding asynchronous work when an asynchronous module or handler signals completion, etc.
// It is meant as a safety net to let developers know early on when they're writing async code
// which doesn't fit our expected patterns and where that code likely has negative side effects.
//
// This flag is respected only by AspNetSynchronizationContext; it has no effect when the
// legacy sync context is in use.
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool AllowAsyncDuringSyncStages {
get {
return SyncContext.AllowAsyncDuringSyncStages;
}
set {
SyncContext.AllowAsyncDuringSyncStages = value;
}
}
/// <devdoc>
/// <para>Retrieves a reference to the application object for the current Http request.</para>
/// </devdoc>
public HttpApplication ApplicationInstance {
get {
return _appInstance;
}
set {
// For integrated pipeline, once this is set to a non-null value, it can only be set to null.
// The setter should never have been made public. It probably happened in 1.0, before it was possible
// to have getter and setter with different accessibility.
if (_isIntegratedPipeline && _appInstance != null && value != null) {
throw new InvalidOperationException(SR.GetString(SR.Application_instance_cannot_be_changed));
}
else {
_appInstance = value;
// Use HttpApplication instance custom allocator provider
if (_isIntegratedPipeline) {
// The provider allows null - everyone should fallback to default implementation
IAllocatorProvider allocator = _appInstance != null ? _appInstance.AllocatorProvider : null;
_response.SetAllocatorProvider(allocator);
((IIS7WorkerRequest)_wr).AllocatorProvider = allocator;
}
}
}
}
/// <devdoc>
/// <para>
/// Retrieves a reference to the application object for the current
/// Http request.
/// </para>
/// </devdoc>
public HttpApplicationState Application {
get { return HttpApplicationFactory.ApplicationState; }
}
// flag to suppress use of custom HttpEncoder registered in web.config
// for example, yellow error pages should use the default encoder rather than a custom encoder
internal bool DisableCustomHttpEncoder {
get;
set;
}
/// <devdoc>
/// <para>
/// Retrieves or assigns a reference to the <see cref='System.Web.IHttpHandler'/>
/// object for the current request.
/// </para>
/// </devdoc>
public IHttpHandler Handler {
get { return _handler;}
set {
_handler = value;
_requiresSessionStateFromHandler = false;
_readOnlySessionStateFromHandler = false;
InAspCompatMode = false;
if (_handler != null) {
if (_handler is IRequiresSessionState) {
_requiresSessionStateFromHandler = true;
}
if (_handler is IReadOnlySessionState) {
_readOnlySessionStateFromHandler = true;
}
Page page = _handler as Page;
if (page != null && page.IsInAspCompatMode) {
InAspCompatMode = true;
}
}
}
}
/// <devdoc>
/// <para>
/// Retrieves or assigns a reference to the <see cref='System.Web.IHttpHandler'/>
/// object for the previous handler;
/// </para>
/// </devdoc>
public IHttpHandler PreviousHandler {
get {
if (_handlerStack == null || _handlerStack.Count == 0)
return null;
return (IHttpHandler)_handlerStack.Peek();
}
}
/// <devdoc>
/// <para>
/// Retrieves or assigns a reference to the <see cref='System.Web.IHttpHandler'/>
/// object for the current executing handler;
/// </para>
/// </devdoc>
private IHttpHandler _currentHandler = null;
public IHttpHandler CurrentHandler {
get {
if (_currentHandler == null)
_currentHandler = _handler;
return _currentHandler;
}
}
internal void RestoreCurrentHandler() {
_currentHandler = (IHttpHandler)_handlerStack.Pop();
}
internal void SetCurrentHandler(IHttpHandler newtHandler) {
if (_handlerStack == null) {
_handlerStack = new Stack();
}
_handlerStack.Push(CurrentHandler);
_currentHandler = newtHandler;
}
/// <devdoc>
/// <para>
/// Set custom mapping handler processing the request <see cref='System.Web.IHttpHandler'/>
/// </para>
/// </devdoc>
public void RemapHandler(IHttpHandler handler) {
EnsureHasNotTransitionedToWebSocket();
IIS7WorkerRequest wr = _wr as IIS7WorkerRequest;
if (wr != null) {
// Remap handler not allowed after ResolveRequestCache notification
if (_notificationContext.CurrentNotification >= RequestNotification.MapRequestHandler) {
throw new InvalidOperationException(SR.GetString(SR.Invoke_before_pipeline_event, "HttpContext.RemapHandler", "HttpApplication.MapRequestHandler"));
}
string handlerTypeName = null;
string handlerName = null;
if (handler != null) {
Type handlerType = handler.GetType();
handlerTypeName = handlerType.AssemblyQualifiedName;
handlerName = handlerType.FullName;
}
wr.SetRemapHandler(handlerTypeName, handlerName);
}
_remapHandler = handler;
}
internal IHttpHandler RemapHandlerInstance {
get {
return _remapHandler;
}
}
/// <devdoc>
/// <para>
/// Retrieves a reference to the target <see cref='System.Web.HttpRequest'/>
/// object for the current request.
/// </para>
/// </devdoc>
public HttpRequest Request {
get {
if (HideRequestResponse)
throw new HttpException(SR.GetString(SR.Request_not_available));
return _request;
}
}
/// <devdoc>
/// <para>
/// Retrieves a reference to the <see cref='System.Web.HttpResponse'/>
/// object for the current response.
/// </para>
/// </devdoc>
public HttpResponse Response {
get {
if (HideRequestResponse || HasWebSocketRequestTransitionCompleted)
throw new HttpException(SR.GetString(SR.Response_not_available));
return _response;
}
}
internal IHttpHandler TopHandler {
get {
if (_handlerStack == null) {
return _handler;
}
object[] handlers = _handlerStack.ToArray();
if (handlers == null || handlers.Length == 0) {
return _handler;
}
return (IHttpHandler)handlers[handlers.Length - 1];
}
}
/// <devdoc>
/// <para>Retrieves a reference to the <see cref='System.Web.TraceContext'/> object for the current
/// response.</para>
/// </devdoc>
public TraceContext Trace {
get {
if (_topTraceContext == null)
_topTraceContext = new TraceContext(this);
return _topTraceContext;
}
}
internal bool TraceIsEnabled {
get {
if (_topTraceContext == null)
return false;
return _topTraceContext.IsEnabled;
}
set {
if (value)
_topTraceContext = new TraceContext(this);
}
}
/// <devdoc>
/// <para>
/// Retrieves a key-value collection that can be used to
/// build up and share data between an <see cref='System.Web.IHttpModule'/> and an <see cref='System.Web.IHttpHandler'/>
/// during a
/// request.
/// </para>
/// </devdoc>
public IDictionary Items {
get {
if (_items == null)
_items = new Hashtable();
return _items;
}
}
/// <devdoc>
/// <para>
/// Gets a reference to the <see cref='System.Web.SessionState'/> instance for the current request.