File: HttpContext.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (2349 lines) | stat: -rw-r--r-- 95,669 bytes parent folder | download | duplicates (6)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
//------------------------------------------------------------------------------
// <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.
        ///    </para>
        /// </devdoc>
        public HttpSessionState Session {
            get {
                if (HasWebSocketRequestTransitionCompleted) {
                    // Session is unavailable at this point
                    return null;
                }

                if (_delayedSessionState) {
                    lock (this) {
                        if (_delayedSessionState) {
                            Debug.Assert(_sessionStateModule != null, "_sessionStateModule != null");

                            // If it's not null, it means we have a delayed session state item
                            _sessionStateModule.InitStateStoreItem(true);
                            _delayedSessionState = false;
                        }
                    }
                }

                return(HttpSessionState)Items[SessionStateUtility.SESSION_KEY];
            }
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        internal void EnsureSessionStateIfNecessary() {
            if (_sessionStateModule == null)
            {
                // If _sessionStateModule is null, we wouldn't be able to call 
                // _sessionStateModule.EnsureStateStoreItemLocked(), so we return here.
                // _sessionStateModule could be null in the following cases,
                // 1. No session state acquired.
                // 2. HttpResponse.Flush() happens after session state being released.
                // 3. The session state module in use is not System.Web.SessionState.SessionStateModule.
                //
                // This method is for the in-framework SessionStateModule only.
                //  OOB SessionStateModule can achieve this by using HttpResponse.AddOnSendingHeaders. 
                return;
            }

            HttpSessionState session = (HttpSessionState)Items[SessionStateUtility.SESSION_KEY];

            if (session != null &&                                 // The session has been initiated
                session.Count > 0 &&                               // The session state is used
                !string.IsNullOrEmpty(session.SessionID)) {        // Ensure the session Id is valid - it will force to create new if didn't exist
                _sessionStateModule.EnsureStateStoreItemLocked();  // Lock the item if in use
            }
        }


        internal void AddHttpSessionStateModule(SessionStateModule module, bool delayed) {
            if (_sessionStateModule != null && _sessionStateModule != module) {
                throw new HttpException(SR.GetString(SR.Cant_have_multiple_session_module));
            }
            _sessionStateModule = module;
            _delayedSessionState = delayed;
        }

        internal void RemoveHttpSessionStateModule() {
            _delayedSessionState = false;
            _sessionStateModule = null;
        }


        /// <devdoc>
        ///    <para>
        ///       Gets a reference to the <see cref='System.Web.HttpServerUtility'/>
        ///       for the current
        ///       request.
        ///    </para>
        /// </devdoc>
        public HttpServerUtility Server {
            get {
                // create only on demand
                if (_server == null)
                    _server = new HttpServerUtility(this);
                return _server;
            }
        }

        // if the context has an error, report it, but only one time
        internal void ReportRuntimeErrorIfExists(ref RequestNotificationStatus status) {
            Exception e = Error;

            if (e == null || _runtimeErrorReported) {
                return;
            }

            // WOS 1921799: custom errors don't work in integrated mode if there's an initialization exception
            if (_notificationContext != null && CurrentModuleIndex == -1) {
                try {
                    IIS7WorkerRequest wr = _wr as IIS7WorkerRequest;
                    if (Request.QueryString["aspxerrorpath"] != null
                        && wr != null
                        && String.IsNullOrEmpty(wr.GetManagedHandlerType())
                        && wr.GetCurrentModuleName() == PipelineRuntime.InitExceptionModuleName) {
                        status = RequestNotificationStatus.Continue;   // allow non-managed handler to execute request
                        return;
                    }
                }
                catch {
                }
            }

            _runtimeErrorReported = true;

            if (HttpRuntime.AppOfflineMessage != null) {
                try {
                    // report app offline error
                    Response.TrySkipIisCustomErrors = true;
                    HttpRuntime.ReportAppOfflineErrorMessage(Response, HttpRuntime.AppOfflineMessage);

                }
                catch {
                }
            }
            else {
                // report error exception
                using (new DisposableHttpContextWrapper(this)) {

                    // if the custom encoder throws, it might interfere with returning error information
                    // to the client, so we force use of the default encoder
                    DisableCustomHttpEncoder = true;

                    // when application is on UNC share the code below must
                    // be run while impersonating the token given by IIS
                    using (new ApplicationImpersonationContext()) {

                        try {
                            try {
                                // try to report error in a way that could possibly throw (a config exception)
                                Response.ReportRuntimeError(e, true /*canThrow*/, false);
                            }
                            catch (Exception eReport) {
                                // report the config error in a way that would not throw
                                Response.ReportRuntimeError(eReport, false /*canThrow*/, false);
                            }
                        }
                        catch (Exception) {
                        }
                    }
                }
            }

            status = RequestNotificationStatus.FinishRequest;
            return;
        }

        /// <devdoc>
        ///    <para>
        ///       Gets the
        ///       first error (if any) accumulated during request processing.
        ///    </para>
        /// </devdoc>
        public Exception Error {
            get {
                if (_tempError != null)
                    return _tempError;
                if (_errors == null || _errors.Count == 0 || _errorCleared)
                    return null;
                return (Exception)_errors[0];
            }
        }

        //
        // Temp error (yet to be caught on app level)
        // to be reported as Server.GetLastError() but could be cleared later
        //
        internal Exception TempError {
            get { return _tempError; }
            set { _tempError = value; }
        }


        /// <devdoc>
        ///    <para>
        ///       An array (collection) of errors accumulated while processing a
        ///       request.
        ///    </para>
        /// </devdoc>
        public Exception[] AllErrors {
            get {
                int n = (_errors != null) ? _errors.Count : 0;

                if (n == 0)
                    return null;

                Exception[] errors = new Exception[n];
                _errors.CopyTo(0, errors, 0, n);
                return errors;
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Registers an error for the current request.
        ///    </para>
        /// </devdoc>
        public void AddError(Exception errorInfo) {
            if (_errors == null)
                _errors = new ArrayList();

            _errors.Add(errorInfo);

            if (_isIntegratedPipeline && _notificationContext != null) {
                // set the error on the current notification context
                _notificationContext.Error = errorInfo;
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Clears all errors for the current request.
        ///    </para>
        /// </devdoc>
        public void ClearError() {
            if (_tempError != null)
                _tempError = null;
            else
                _errorCleared = true;

            if (_isIntegratedPipeline && _notificationContext != null) {
                // clear the error on the current notification context
                _notificationContext.Error = null;
            }
        }


        /// <devdoc>
        ///    <para>
        ///       IPrincipal security information.
        ///    </para>
        /// </devdoc>
        public IPrincipal User {
            get { return _principalContainer.Principal; }

            [SecurityPermission(SecurityAction.Demand, ControlPrincipal=true)]
            set {
                SetPrincipalNoDemand(value);
            }
        }

        IPrincipal IPrincipalContainer.Principal {
            get;
            set;
        }

        // route all internals call to the principal (that don't have luring attacks)
        // through this method so we can centralize reporting
        // Before this, some auth modules were assigning directly to _user
        internal void SetPrincipalNoDemand(IPrincipal principal, bool needToSetNativePrincipal) {
            _principalContainer.Principal = principal;

            // push changes through to native side
            if (needToSetNativePrincipal
                && _isIntegratedPipeline
                && _notificationContext.CurrentNotification == RequestNotification.AuthenticateRequest) {

                IntPtr pManagedPrincipal = IntPtr.Zero;
                IIS7WorkerRequest wr = (IIS7WorkerRequest)_wr;
                wr.SetPrincipal(principal);
            }
        }

        internal void SetPrincipalNoDemand(IPrincipal principal) {
            SetPrincipalNoDemand(principal, true /*needToSetNativePrincipal*/);
        }

        [DoNotReset]
        internal bool _ProfileDelayLoad = false;

        public ProfileBase  Profile {
            get {
                if (_Profile == null && _ProfileDelayLoad)
                    _Profile = ProfileBase.Create(Request.IsAuthenticated ? User.Identity.Name : Request.AnonymousID, Request.IsAuthenticated);
                return _Profile;
            }
        }

        internal SessionStateBehavior SessionStateBehavior { get; set; }

        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
          Justification = "An internal property already exists. This method does additional work.")]
        public void SetSessionStateBehavior(SessionStateBehavior sessionStateBehavior) {
            if (_notificationContext != null && _notificationContext.CurrentNotification >= RequestNotification.AcquireRequestState) {
                throw new InvalidOperationException(SR.GetString(SR.Invoke_before_pipeline_event, "HttpContext.SetSessionStateBehavior", "HttpApplication.AcquireRequestState"));
            }

            SessionStateBehavior = sessionStateBehavior;
        }


        public bool SkipAuthorization {
            get { return _skipAuthorization;}

            [SecurityPermission(SecurityAction.Demand, ControlPrincipal=true)]
            set {
                SetSkipAuthorizationNoDemand(value, false);
            }
        }

        internal void SetSkipAuthorizationNoDemand(bool value, bool managedOnly)
        {
            if (HttpRuntime.UseIntegratedPipeline
                && !managedOnly
                && value != _skipAuthorization) {

                // For integrated mode, persist changes to SkipAuthorization
                // in the IS_LOGIN_PAGE server variable.  When this server variable exists
                // and the value is not "0", IIS skips authorization.

                _request.SetSkipAuthorization(value);
            }

            _skipAuthorization = value;
        }

        // Pointer to the RootedObjects element, which contains information that needs to be flowed
        // between the HttpContext and the WebSocket, such as the current principal.
        [DoNotReset]
        private RootedObjects _rootedObjects;
        
        internal RootedObjects RootedObjects {
            get {
                return _rootedObjects;
            }
            set {
                // Sync the Principal between the containers
                SwitchPrincipalContainer(value);
                _rootedObjects = value;
            }
        }

        private void SwitchPrincipalContainer(IPrincipalContainer newPrincipalContainer) {
            if (newPrincipalContainer == null) {
                newPrincipalContainer = this;
            }

            // Ensure new container contains the current principal
            IPrincipal currentPrincipal = _principalContainer.Principal;
            newPrincipalContainer.Principal = currentPrincipal;
            _principalContainer = newPrincipalContainer;
        }

        /// <devdoc>
        ///    <para>
        ///       Is this request in debug mode?
        ///    </para>
        /// </devdoc>
        public bool IsDebuggingEnabled {
            get {
                try {
                    return CompilationUtil.IsDebuggingEnabled(this);
                }
                catch {
                    // in case of config errors don't throw
                    return false;
                }
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Is this custom error enabled for this request?
        ///    </para>
        /// </devdoc>
        public bool IsCustomErrorEnabled {
            get {
                return CustomErrorsSection.GetSettings(this).CustomErrorsEnabled(_request);
            }
        }

        internal TemplateControl TemplateControl {
            get {
                return _templateControl;
            }
            set {
                _templateControl = value;
            }
        }


        /// <devdoc>
        ///    <para>Gets the initial timestamp of the current request.</para>
        /// </devdoc>
        public DateTime Timestamp {
            get { return _utcTimestamp.ToLocalTime();}
        }

        internal DateTime UtcTimestamp {
            get { return _utcTimestamp;}
        }

        internal HttpWorkerRequest WorkerRequest {
            get { return _wr;}
        }


        /// <devdoc>
        ///    <para>
        ///       Gets a reference to the System.Web.Cache.Cache object for the current request.
        ///    </para>
        /// </devdoc>
        public Cache Cache {
            get { return HttpRuntime.Cache;}
        }

        /// <summary>
        /// Gets a reference to the System.Web.Instrumentation.PageInstrumentationService instance for this request. Guaranteed not to be null (barring private reflection magic).
        /// </summary>
        public PageInstrumentationService PageInstrumentation {
            get { 
                if(_pageInstrumentationService == null) {
                    _pageInstrumentationService = new PageInstrumentationService();
                }
                return _pageInstrumentationService;
            }
        }

        /*
         * The virtual path used to get config settings.  This allows the user
         * to specify a non default config path, without having to pass it to every
         * configuration call.
         */
        internal VirtualPath ConfigurationPath {
            get {
                if (_configurationPath == null)
                    _configurationPath = _request.FilePathObject;

                return _configurationPath;
            }

            set {
                _configurationPath = value;
                _configurationPathData = null;
                _filePathData = null;
            }
        }

        internal CachedPathData GetFilePathData() {
            if (_filePathData == null) {
                _filePathData = CachedPathData.GetVirtualPathData(_request.FilePathObject, false);
            }

            return _filePathData;
        }

        internal CachedPathData GetConfigurationPathData() {
            if (_configurationPath == null) {
                return GetFilePathData();
            }

            // 
            if (_configurationPathData == null) {
                _configurationPathData = CachedPathData.GetVirtualPathData(_configurationPath, true);
            }

            return _configurationPathData;
        }

        internal CachedPathData GetPathData(VirtualPath path) {
            if (path != null) {
                if (path.Equals(_request.FilePathObject)) {
                    return GetFilePathData();
                }

                if (_configurationPath != null && path.Equals(_configurationPath)) {
                    return GetConfigurationPathData();
                }
            }

            return CachedPathData.GetVirtualPathData(path, false);
        }

        internal void FinishRequestForCachedPathData(int statusCode) {
            // Remove the cached path data for a file path if the first request for it
            // does not succeed due to a bad request. Otherwise we could be vulnerable
            // to a DOS attack.
            if (_filePathData != null && !_filePathData.CompletedFirstRequest) {
                if (400 <= statusCode && statusCode < 500) {
                    CachedPathData.RemoveBadPathData(_filePathData);
                }
                else {
                    CachedPathData.MarkCompleted(_filePathData);
                }
            }
        }

        /*
         * Uses the Config system to get the specified configuraiton
         */
        [Obsolete("The recommended alternative is System.Web.Configuration.WebConfigurationManager.GetWebApplicationSection in System.Web.dll. http://go.microsoft.com/fwlink/?linkid=14202")]
        public static object GetAppConfig(String name) {
            return WebConfigurationManager.GetWebApplicationSection(name);
        }

        [Obsolete("The recommended alternative is System.Web.HttpContext.GetSection in System.Web.dll. http://go.microsoft.com/fwlink/?linkid=14202")]
        public object GetConfig(String name) {
            return GetSection(name);
        }

        public object GetSection(String sectionName) {
            if (HttpConfigurationSystem.UseHttpConfigurationSystem) {
                return GetConfigurationPathData().ConfigRecord.GetSection(sectionName);
            }
            else {
                return ConfigurationManager.GetSection(sectionName);
            }
        }

        internal RuntimeConfig GetRuntimeConfig() {
            return GetConfigurationPathData().RuntimeConfig;
        }

        internal RuntimeConfig GetRuntimeConfig(VirtualPath path) {
            return GetPathData(path).RuntimeConfig;
        }

        public void RewritePath(String path) {
            RewritePath(path, true);
        }

        /*
         * Called by the URL rewrite module to modify the path for downstream modules
         */

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void RewritePath(String path, bool rebaseClientPath) {
            if (path == null)
                throw new ArgumentNullException("path");

            // extract query string
            String qs = null;
            int iqs = path.IndexOf('?');
            if (iqs >= 0) {
                qs = (iqs < path.Length-1) ? path.Substring(iqs+1) : String.Empty;
                path = path.Substring(0, iqs);
            }

            // resolve relative path
            VirtualPath virtualPath = VirtualPath.Create(path);
            virtualPath = Request.FilePathObject.Combine(virtualPath);

            // disallow paths outside of app
            virtualPath.FailIfNotWithinAppRoot();

            // clear things that depend on path
            ConfigurationPath = null;

            // rewrite path on request
            Request.InternalRewritePath(virtualPath, qs, rebaseClientPath);
        }


        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public void RewritePath(String filePath, String pathInfo, String queryString) {
            RewritePath(VirtualPath.CreateAllowNull(filePath), VirtualPath.CreateAllowNull(pathInfo),
                queryString, false /*setClientFilePath*/);
        }
        public void RewritePath(string filePath, string pathInfo, String queryString, bool setClientFilePath)
        {
            RewritePath(VirtualPath.CreateAllowNull(filePath), VirtualPath.CreateAllowNull(pathInfo), queryString, setClientFilePath);
        }
        internal void RewritePath(VirtualPath filePath, VirtualPath pathInfo, String queryString, bool setClientFilePath) {
            EnsureHasNotTransitionedToWebSocket();

            if (filePath == null)
                throw new ArgumentNullException("filePath");

            // resolve relative path
            filePath = Request.FilePathObject.Combine(filePath);

            // disallow paths outside of app
            filePath.FailIfNotWithinAppRoot();

            // clear things that depend on path
            ConfigurationPath = null;

            // rewrite path on request
            Request.InternalRewritePath(filePath, pathInfo, queryString, setClientFilePath);
        }

        internal CultureInfo DynamicCulture {
            get { return _dynamicCulture; }
            set { _dynamicCulture = value; }
        }

        internal CultureInfo DynamicUICulture {
            get { return _dynamicUICulture; }
            set { _dynamicUICulture = value; }
        }

        public static object GetGlobalResourceObject(string classKey, string resourceKey) {
            return GetGlobalResourceObject(classKey, resourceKey, null);
        }

        public static object GetGlobalResourceObject(string classKey, string resourceKey, CultureInfo culture) {
            return ResourceExpressionBuilder.GetGlobalResourceObject(classKey, resourceKey, null, null, culture);
        }

        public static object GetLocalResourceObject(string virtualPath, string resourceKey) {
            return GetLocalResourceObject(virtualPath, resourceKey, null);
        }

        public static object GetLocalResourceObject(string virtualPath, string resourceKey, CultureInfo culture) {
            IResourceProvider pageProvider = ResourceExpressionBuilder.GetLocalResourceProvider(
                VirtualPath.Create(virtualPath));
            return ResourceExpressionBuilder.GetResourceObject(pageProvider, resourceKey, culture);
        }

        internal int ServerExecuteDepth {
            get { return _serverExecuteDepth; }
            set { _serverExecuteDepth = value; }
        }

        internal bool PreventPostback {
            get { return _preventPostback; }
            set { _preventPostback = value; }
        }

        //
        // Timeout support
        //

        internal Thread CurrentThread {
            get {
                return _thread;
            }
            set {
                _thread = value;
            }
        }

        // Property is thread-safe since needs to be accessed by RequestTimeoutManager in addition to
        // normal request threads.
        internal TimeSpan Timeout {
            get {
                long ticks = EnsureTimeout();
                return TimeSpan.FromTicks(ticks);
            }

            set {
                Interlocked.Exchange(ref _timeoutTicks, value.Ticks);
            }
        }

        // Access via HttpRequest.TimedOutToken instead.
        internal CancellationToken TimedOutToken {
            get {
                // If we are the first call site to observe the token, then create it in the non-canceled state.
                CancellationTokenHelper helper = LazyInitializer.EnsureInitialized(ref _timeoutCancellationTokenHelper, () => new CancellationTokenHelper(canceled: false));
                return helper.Token;
            }
        }

        /// <summary>
        /// Determines whether the ASP.NET runtime calls Thread.Abort() on the thread servicing this request when
        /// the request times out. Default value is 'true'.
        /// </summary>
        /// <remarks>
        /// Handlers and modules that are using Request.TimedOutToken to implement cooperative cancellation may
        /// wish to disable the rude Thread.Abort behavior that ASP.NET has historically performed when a request
        /// times out. This can help developers make sure that their g----ful cancellation + cleanup routines
        /// will run without interruption by ASP.NET.
        /// 
        /// The rules for determining when a thread is aborted are somewhat complicated, so applications shouldn't
        /// try to depend on them. Currently, the behavior is:
        /// 
        /// - The thread will be aborted at some point after Request.TimedOutToken is canceled. The abort might not
        ///   occur immediately afterward, as the "should Thread.Abort" timer is separate from the "should signal
        ///   the CancellationToken" timer.
        /// 
        /// - We generally don't abort threads that are processing async modules or handlers. There are some
        ///   exceptions. E.g., during certain parts of the lifecycle for async WebForms pages, the thread can be
        ///   a candidate to be aborted when a timeout occurs.
        ///   
        /// If a developer sets this property to 'false', ASP.NET will not automatically display a "Request timed
        /// out" YSOD when a timeout occurs. If this happens the application is responsible for setting the response
        /// content appropriately.
        /// </remarks>
        public bool ThreadAbortOnTimeout {
            get { return Volatile.Read(ref _threadAbortOnTimeout); }
            set { Volatile.Write(ref _threadAbortOnTimeout, value); }
        }

        private void DisposeTimedOutToken() {
            // If we are the first call site to observe the token, then create it in the disposed state.
            CancellationTokenHelper helper = LazyInitializer.EnsureInitialized(ref _timeoutCancellationTokenHelper, () => CancellationTokenHelper.StaticDisposed);
            helper.Dispose();
        }

        internal long EnsureTimeout() {
            // Calls to Volatile.* are atomic, even for 64-bit fields.
            long ticks = Volatile.Read(ref _timeoutTicks);
            if (ticks == -1) {
                // Only go to config if the value hasn't yet been initialized.
                HttpRuntimeSection cfg = RuntimeConfig.GetConfig(this).HttpRuntime;
                ticks = cfg.ExecutionTimeout.Ticks;

                // If another thread already came in and initialized _timeoutTicks,
                // return that value instead of the value we just read from config.
                long originalTicks = Interlocked.CompareExchange(ref _timeoutTicks, ticks, -1);
                if (originalTicks != -1) {
                    ticks = originalTicks;
                }
            }

            return ticks;
        }

        internal DoubleLink TimeoutLink {
            get { return _timeoutLink;}
            set { _timeoutLink = value;}
        }

        /*

        Notes on the following 5 functions:

        Execution can be cancelled only during certain periods, when inside the catch
        block for ThreadAbortException.  These periods are marked with the value of
        _timeoutState of 1.

        There is potential [rare] race condition when the timeout thread would call
        thread.abort but the execution logic in the meantime escapes the catch block.
        To avoid such race conditions _timeoutState of -1 (cancelled) is introduced.
        The timeout thread sets _timeoutState to -1 before thread abort and the
        unwinding logic just waits for the exception in this case. The wait cannot
        be done in EndCancellablePeriod because the function is call from inside of
        a finally block and thus would wait indefinetely. That's why another function
        WaitForExceptionIfCancelled had been added.

        Originally _timeoutStartTime was set in BeginCancellablePeriod. However, that means
        we'll call UtcNow everytime we call ExecuteStep, which is too expensive. So to save
        CPU time we created a new method SetStartTime() which is called by the caller of
        ExecuteStep.

        */

        internal void BeginCancellablePeriod() {
            // It could be caused by an exception in OnThreadStart
            if (Volatile.Read(ref _timeoutStartTimeUtcTicks) == -1) {
                SetStartTime();
            }

            Volatile.Write(ref _timeoutState, 1);
        }

        internal void SetStartTime() {
            Interlocked.Exchange(ref _timeoutStartTimeUtcTicks, DateTime.UtcNow.Ticks);
        }

        internal void EndCancellablePeriod() {
            Interlocked.CompareExchange(ref _timeoutState, 0, 1);
        }

        internal void WaitForExceptionIfCancelled() {
            while (Volatile.Read(ref _timeoutState) == -1)
                Thread.Sleep(100);
        }

        internal bool IsInCancellablePeriod {
            get { return (Volatile.Read(ref _timeoutState) == 1); }
        }

        internal Thread MustTimeout(DateTime utcNow) {
            // Note: The TimedOutToken is keyed off of the HttpContext creation time, not the most recent async
            // completion time (like the Thread.Abort logic later in this method).

            if (_utcTimestamp + Timeout < utcNow) {
                // If we are the first call site to observe the token, then create it in the canceled state.
                CancellationTokenHelper helper = LazyInitializer.EnsureInitialized(ref _timeoutCancellationTokenHelper, () => new CancellationTokenHelper(canceled: true));
                helper.Cancel();
            }

            if (Volatile.Read(ref _timeoutState) == 1 && ThreadAbortOnTimeout) {  // fast check
                long expirationUtcTicks = Volatile.Read(ref _timeoutStartTimeUtcTicks) + Timeout.Ticks; // don't care about overflow
                if (expirationUtcTicks < utcNow.Ticks) {
                    // don't abort in debug mode
                    try {
                        if (CompilationUtil.IsDebuggingEnabled(this) || System.Diagnostics.Debugger.IsAttached)
                            return null;
                    }
                    catch {
                        // ignore config errors
                        return null;
                    }

                    // abort the thread only if in cancelable state, avoiding race conditions
                    // the caller MUST timeout if the return is true
                    if (Interlocked.CompareExchange(ref _timeoutState, -1, 1) == 1) {
                        if (_wr.IsInReadEntitySync) {
                            AbortConnection();
                        }
                        return _thread;
                    }
                }
            }

            return null;
        }

        internal bool HasTimeoutExpired {
            get {
                // Check if it is allowed to timeout
                if (Volatile.Read(ref _timeoutState) != 1 || !ThreadAbortOnTimeout) {
                    return false;
                }

                // Check if the timeout has expired
                long expirationUtcTicks = Volatile.Read(ref _timeoutStartTimeUtcTicks) + Timeout.Ticks; // don't care about overflow
                if (expirationUtcTicks >= DateTime.UtcNow.Ticks) {
                    return false;
                }

                // Dont't timeout when in debug
                try {
                    if (CompilationUtil.IsDebuggingEnabled(this) || System.Diagnostics.Debugger.IsAttached) {
                        return false;
                    }
                }
                catch {
                    // ignore config errors
                    return false;
                }

                return true;
            }
        }

        // call a delegate within cancellable period (possibly throwing timeout exception)
        internal void InvokeCancellableCallback(WaitCallback callback, Object state) {
            if (IsInCancellablePeriod) {
                // call directly
                callback(state);
                return;
            }

            try {
                BeginCancellablePeriod();  // request can be cancelled from this point

                try {
                    callback(state);
                }
                finally {
                    EndCancellablePeriod();  // request can be cancelled until this point
                }

                WaitForExceptionIfCancelled();  // wait outside of finally
            }
            catch (ThreadAbortException e) {
                if (e.ExceptionState != null &&
                    e.ExceptionState is HttpApplication.CancelModuleException &&
                    ((HttpApplication.CancelModuleException)e.ExceptionState).Timeout) {

                    Thread.ResetAbort();
                    PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_TIMED_OUT);

                    throw new HttpException(SR.GetString(SR.Request_timed_out),
                                        null, WebEventCodes.RuntimeErrorRequestAbort);
                }
            }
        }

        internal void PushTraceContext() {
            if (_traceContextStack == null) {
                _traceContextStack = new Stack();
            }

            // push current TraceContext on stack
            _traceContextStack.Push(_topTraceContext);

            // now make a new one for the top if necessary
            if (_topTraceContext != null) {
                TraceContext tc = new TraceContext(this);
                _topTraceContext.CopySettingsTo(tc);
                _topTraceContext = tc;
            }
        }

        internal void PopTraceContext() {
            Debug.Assert(_traceContextStack != null);
            _topTraceContext = (TraceContext) _traceContextStack.Pop();
        }

        internal bool RequestRequiresAuthorization()  {
#if !FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features
            // if current user is anonymous, then trivially, this page does not require authorization
            if (!User.Identity.IsAuthenticated)
                return false;

            // Ask each of the authorization modules
            return
                ( FileAuthorizationModule.RequestRequiresAuthorization(this) ||
                  UrlAuthorizationModule.RequestRequiresAuthorization(this)   );
#else // !FEATURE_PAL
                return false; // ROTORTODO
#endif // !FEATURE_PAL
        }

        internal int CallISAPI(UnsafeNativeMethods.CallISAPIFunc iFunction, byte [] bufIn, byte [] bufOut) {

            if (_wr == null || !(_wr is System.Web.Hosting.ISAPIWorkerRequest))
                throw new HttpException(SR.GetString(SR.Cannot_call_ISAPI_functions));
#if !FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features
            return ((System.Web.Hosting.ISAPIWorkerRequest) _wr).CallISAPI(iFunction, bufIn, bufOut);
#else // !FEATURE_PAL
                throw new NotImplementedException ("ROTORTODO");
#endif // !FEATURE_PAL
        }

        internal void SendEmptyResponse() {
#if !FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features
            if (_wr != null  && (_wr is System.Web.Hosting.ISAPIWorkerRequest))
                ((System.Web.Hosting.ISAPIWorkerRequest) _wr).SendEmptyResponse();
#endif // !FEATURE_PAL
        }

        private  CookielessHelperClass _CookielessHelper;
        internal CookielessHelperClass  CookielessHelper {
            get {
                if (_CookielessHelper == null)
                    _CookielessHelper = new CookielessHelperClass(this);
                return _CookielessHelper;
            }
        }


        // When a thread enters the pipeline, we may need to set the cookie in the CallContext.
        internal void ResetSqlDependencyCookie() {
            if (_sqlDependencyCookie != null) {
                System.Runtime.Remoting.Messaging.CallContext.LogicalSetData(SqlCacheDependency.SQL9_OUTPUT_CACHE_DEPENDENCY_COOKIE, _sqlDependencyCookie);
            }
        }

        // When a thread leaves the pipeline, we may need to remove the cookie from the CallContext.
        internal void RemoveSqlDependencyCookie() {
            if (_sqlDependencyCookie != null) {
                System.Runtime.Remoting.Messaging.CallContext.LogicalSetData(SqlCacheDependency.SQL9_OUTPUT_CACHE_DEPENDENCY_COOKIE, null);
            }
        }

        internal string SqlDependencyCookie {
            get {
                return _sqlDependencyCookie;
            }

            set {
                _sqlDependencyCookie = value;
                System.Runtime.Remoting.Messaging.CallContext.LogicalSetData(SqlCacheDependency.SQL9_OUTPUT_CACHE_DEPENDENCY_COOKIE, value);
            }
        }

        //
        // integrated pipeline related
        //
        internal NotificationContext NotificationContext {
            get { return _notificationContext; }
            set { _notificationContext = value; }
        }

        public RequestNotification CurrentNotification {
            get {
                EnsureHasNotTransitionedToWebSocket();

                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }

                return _notificationContext.CurrentNotification;
            }
            internal set {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }

                _notificationContext.CurrentNotification = value;
            }
        }

        internal bool IsChangeInServerVars {
            get { return (_notificationContext.CurrentNotificationFlags & FLAG_CHANGE_IN_SERVER_VARIABLES) == FLAG_CHANGE_IN_SERVER_VARIABLES; }
        }

        internal bool IsChangeInRequestHeaders {
            get { return (_notificationContext.CurrentNotificationFlags & FLAG_CHANGE_IN_REQUEST_HEADERS) == FLAG_CHANGE_IN_REQUEST_HEADERS; }
        }

        internal bool IsChangeInResponseHeaders {
            get { return (_notificationContext.CurrentNotificationFlags & FLAG_CHANGE_IN_RESPONSE_HEADERS) == FLAG_CHANGE_IN_RESPONSE_HEADERS; }
        }

        internal bool IsChangeInResponseStatus {
            get { return (_notificationContext.CurrentNotificationFlags & FLAG_CHANGE_IN_RESPONSE_STATUS) == FLAG_CHANGE_IN_RESPONSE_STATUS; }
        }

        internal bool IsChangeInUserPrincipal {
            get { return (_notificationContext.CurrentNotificationFlags & FLAG_CHANGE_IN_USER_OBJECT) == FLAG_CHANGE_IN_USER_OBJECT; }
        }

        internal bool IsRuntimeErrorReported {
            get { return _runtimeErrorReported; }
        }

        internal bool IsSendResponseHeaders {
            get { return (_notificationContext.CurrentNotificationFlags & FLAG_SEND_RESPONSE_HEADERS) == FLAG_SEND_RESPONSE_HEADERS; }
        }

        internal void SetImpersonationEnabled() {
            IdentitySection c = RuntimeConfig.GetConfig(this).Identity;
            _impersonationEnabled = (c != null && c.Impersonate);
        }

        internal bool UsesImpersonation {
            get {
                // if we're on a UNC share and we have a UNC token, then use impersonation for all notifications
                if (HttpRuntime.IsOnUNCShareInternal && HostingEnvironment.ApplicationIdentityToken != IntPtr.Zero) {
                    return true;
                }
                // if <identity impersonate=/> is false, then don't use impersonation
                if (!_impersonationEnabled) {
                    return false;
                }
                // the notification context won't be available after we have completed the transition
                if (HasWebSocketRequestTransitionCompleted) {
                    return true;
                }

                // if this notification is after AuthenticateRequest and not a SendResponse notification, use impersonation
                return (((_notificationContext.CurrentNotification == RequestNotification.AuthenticateRequest && _notificationContext.IsPostNotification)
                        || _notificationContext.CurrentNotification > RequestNotification.AuthenticateRequest)
                        && _notificationContext.CurrentNotification != RequestNotification.SendResponse);
            }
        }

        internal bool AreResponseHeadersSent {
            get { return (_notificationContext.CurrentNotificationFlags & FLAG_RESPONSE_HEADERS_SENT) == FLAG_RESPONSE_HEADERS_SENT; }
        }

        internal bool NeedToInitializeApp() {
            bool needToInit = !_isAppInitialized;
            if (needToInit) {
                _isAppInitialized = true;
            }
            return needToInit;
        }

        // flags passed in on the call to PipelineRuntime::ProcessRequestNotification
        internal int CurrentNotificationFlags {
            get {
                return _notificationContext.CurrentNotificationFlags;
            }
            set {
                _notificationContext.CurrentNotificationFlags = value;
            }
        }

        // index of the current "module" running the request
        // into the application module array
        internal int CurrentModuleIndex {
            get {
                return _notificationContext.CurrentModuleIndex;
            }
            set {
                _notificationContext.CurrentModuleIndex = value;
            }
        }

        // Each module has a PipelineModuleStepContainer
        // which stores/manages a list of event handlers
        // that correspond to each RequestNotification.
        // CurrentModuleEventIndex is the index (for the current
        // module) of the current event handler.
        // This will be greater than one when a single
        // module registers multiple delegates for a single event.
        // e.g.
        // app.BeginRequest += Foo;
        // app.BeginRequest += Bar;
        internal int CurrentModuleEventIndex {
            get {
                return _notificationContext.CurrentModuleEventIndex;
            }
            set {
                _notificationContext.CurrentModuleEventIndex = value;
            }
        }

        internal void DisableNotifications(RequestNotification notifications, RequestNotification postNotifications) {
            IIS7WorkerRequest wr = _wr as IIS7WorkerRequest;
            if (null != wr) {
                wr.DisableNotifications(notifications, postNotifications);
            }
        }

        public bool IsPostNotification {
            get {
                EnsureHasNotTransitionedToWebSocket();

                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                return _notificationContext.IsPostNotification;
            }
            internal set {
                if (!HttpRuntime.UseIntegratedPipeline) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }
                _notificationContext.IsPostNotification = value;
            }

        }

        // user token for the request
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This is a safe critical method.")]
        internal IntPtr ClientIdentityToken {
            get {
                if (_wr != null) {
                    return _wr.GetUserToken();
                }
                else {
                    return IntPtr.Zero;
                }
            }
        }

        // is configured to impersonate client?
        internal bool IsClientImpersonationConfigured {
            get {
                try {
                    IdentitySection c = RuntimeConfig.GetConfig(this).Identity;
                    return (c != null && c.Impersonate && c.ImpersonateToken == IntPtr.Zero);
                }
                catch {
                    // this property should not throw as it is used in the error reporting pass
                    // config errors will be reported elsewhere
                    return false;
                }
            }
        }

        internal IntPtr ImpersonationToken {
            get {
                // by default use app identity
                IntPtr token = HostingEnvironment.ApplicationIdentityToken;
                IdentitySection c = RuntimeConfig.GetConfig(this).Identity;
                if (c != null) {
                    if (c.Impersonate) {
                        token = (c.ImpersonateToken != IntPtr.Zero) ? c.ImpersonateToken : ClientIdentityToken;
                    }
                    else {
                        // for non-UNC case impersonate="false" means "don't impersonate",
                        // but there is a special case for UNC shares - even if
                        // impersonate="false" we still impersonate the UNC identity
                        // (hosting identity). and this is how v1.x works as well
                        if (!HttpRuntime.IsOnUNCShareInternal) {
                            token = IntPtr.Zero;
                        }
                    }
                }
                return token;
            }
        }

        internal AspNetSynchronizationContextBase SyncContext {
            get {
                if (_syncContext == null) {
                    _syncContext = CreateNewAspNetSynchronizationContext();
                }

                return _syncContext;
            }
            set {
                _syncContext = value;
            }
        }

        internal AspNetSynchronizationContextBase InstallNewAspNetSynchronizationContext() {
            AspNetSynchronizationContextBase syncContext = _syncContext;

            if (syncContext != null && syncContext == AsyncOperationManager.SynchronizationContext) {
                // using current ASP.NET synchronization context - switch it
                _syncContext = CreateNewAspNetSynchronizationContext();
                AsyncOperationManager.SynchronizationContext = _syncContext;
                return syncContext;
            }

            return null;
        }

        private AspNetSynchronizationContextBase CreateNewAspNetSynchronizationContext() {
            if (!AppSettings.UseTaskFriendlySynchronizationContext) {
                return new LegacyAspNetSynchronizationContext(ApplicationInstance);
            }
            else {
                return new AspNetSynchronizationContext(ApplicationInstance);
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This is a safe critical method.")]
        internal void RestoreSavedAspNetSynchronizationContext(AspNetSynchronizationContextBase syncContext) {
            AsyncOperationManager.SynchronizationContext = syncContext;
            _syncContext = syncContext;
        }

        internal string[] UserLanguagesFromContext() {
            return (Request != null) ? Request.UserLanguages : null;
        }

        // References should be nulled a.s.a.p. to reduce working set
        internal void ClearReferences() {
            _appInstance = null;
            _handler = null;
            _handlerStack = null;
            _currentHandler = null;
            _remapHandler = null;
            if (_isIntegratedPipeline) {
                if (!HasWebSocketRequestTransitionStarted) {
                    // Items is also used by AspNetWebSocketContext and should only be cleared if we're not transitioning to WebSockets
                    _items = null;
                }
                _syncContext = null;
            }
        }

        internal void CompleteTransitionToWebSocket() {
            ClearReferencesForWebSocketProcessing();

            // transition: TransitionStarted -> TransitionCompleted
            TransitionToWebSocketState(WebSocketTransitionState.TransitionCompleted);
        }

        // This is much stronger than just ClearReferences; it tries to free absolutely as much memory as possible.
        // Some necessary items (like _wr, etc.) are preserved. The reason we want to modify this particular instance
        // in-place rather than create a new instance is that it is likely that references to this object still exist,
        // and we don't want the existence of those references to cause memory leaks.
        private void ClearReferencesForWebSocketProcessing() {
            HttpResponse response = _response;

            // everything not marked [DoNotReset] should be eligible for garbage collection
            ReflectionUtil.Reset(this);

            // Miscellaneous steps:
            _request.ClearReferencesForWebSocketProcessing(); // also clean up the HttpRequest instance
            if (response != null) {
                // HttpResponse is off-limits, but it is possible that the developer accidentally maintained a reference
                // to it, e.g. via a closure. We'll release the HttpResponse's references to all its data to prevent
                // this from causing memory problems.
                ReflectionUtil.Reset(response);
            }
        }

        internal CultureInfo CultureFromConfig(string configString, bool requireSpecific) {
            //auto
            if(StringUtil.EqualsIgnoreCase(configString, HttpApplication.AutoCulture)) {
                string[] userLanguages = UserLanguagesFromContext();
                if (userLanguages != null) {
                    try {
                        return CultureUtil.CreateReadOnlyCulture(userLanguages, requireSpecific);
                    }
                    catch {
                        return null;
                    }
                }
                else {
                    return null;
                }
            }
            else if(StringUtil.StringStartsWithIgnoreCase(configString, "auto:")) {
                string[] userLanguages = UserLanguagesFromContext();
                if (userLanguages != null) {
                    try {
                        return CultureUtil.CreateReadOnlyCulture(userLanguages, requireSpecific);
                    }
                    catch {
                        return CultureUtil.CreateReadOnlyCulture(configString.Substring(5 /* "auto:".Length */), requireSpecific);
                    }
                }
                else {
                    return CultureUtil.CreateReadOnlyCulture(configString.Substring(5 /* "auto:".Length */), requireSpecific);
                }
            }

            return CultureUtil.CreateReadOnlyCulture(configString, requireSpecific);
        }

        private enum WebSocketInitStatus {
            Success, // iiswsock.dll is active and has told us that the current request is a WebSocket request
            RequiresIntegratedMode, // WebSockets requires integrated mode, and the current server is not Integrated mode
            CannotCallFromBeginRequest, // We need to wait for BeginRequest to complete before the module has set the server variables
            NativeModuleNotEnabled, // iiswsock.dll isn't active in the pipeline
            NotAWebSocketRequest, // iiswsock.dll is active, but the current request is not a WebSocket request
            CurrentRequestIsChildRequest, // We are currently inside of a child request (IHttpContext::ExecuteRequest)
        }

        private void AbortConnection() {
            IIS7WorkerRequest wr = _wr as IIS7WorkerRequest;

            if (wr != null) { 
                // Direct API Abort is suported in integrated mode only
                wr.AbortConnection();
            }
            else {
                // Close in classic mode acts as Abort (see HSE_REQ_CLOSE_CONNECTION) 
                // It closes the underlined connection
                _wr.CloseConnection();
            }
        }
    }

    //
    // Helper class to add/remove HttpContext to/from CallContext
    //
    // using (new DisposableHttpContextWrapper(context)) {
    //     // this code will have HttpContext.Current working
    // }
    //

    internal class DisposableHttpContextWrapper : IDisposable {
        private bool _needToUndo;
        private HttpContext _savedContext;

        internal static HttpContext SwitchContext(HttpContext context) {
            return ContextBase.SwitchContext(context) as HttpContext;
        }

        internal DisposableHttpContextWrapper(HttpContext context) {
            if (context != null) {
                _savedContext = SwitchContext(context);
                _needToUndo = (_savedContext != context);
            }
        }

        void IDisposable.Dispose() {
            if (_needToUndo) {
                SwitchContext(_savedContext);
                _savedContext = null;
                _needToUndo = false;
            }
        }
    }
}