Welcome to mirror list, hosted at ThFree Co, Russian Federation.

HttpResponse.cs « System.Web « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: b92ce62520ba19dc4df09601e85545381237d6a8 (plain)
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
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
//------------------------------------------------------------------------------
// <copyright file="HttpResponse.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

/*
 * Response intrinsic
 */
namespace System.Web {

    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Runtime.Serialization;
    using System.IO;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Globalization;
    using System.Web.Util;
    using System.Web.Hosting;
    using System.Web.Caching;
    using System.Web.Configuration;
    using System.Web.Routing;
    using System.Web.UI;
    using System.Configuration;
    using System.Security.Permissions;
    using System.Web.Management;
    using System.Diagnostics.CodeAnalysis;


    /// <devdoc>
    ///    <para>Used in HttpResponse.WriteSubstitution.</para>
    /// </devdoc>
    public delegate String HttpResponseSubstitutionCallback(HttpContext context);


    /// <devdoc>
    ///    <para> Enables type-safe server to browser communication. Used to
    ///       send Http output to a client.</para>
    /// </devdoc>
    public sealed class HttpResponse {
        private HttpWorkerRequest _wr;              // some response have HttpWorkerRequest
        private HttpContext _context;               // context
        private HttpWriter _httpWriter;             // and HttpWriter
        private TextWriter _writer;                 // others just have Writer

        private HttpHeaderCollection _headers;      // response header collection (IIS7+)

        private bool _headersWritten;
        private bool _completed;    // after final flush
        private bool _ended;        // after response.end or execute url
        private bool _endRequiresObservation; // whether there was a pending call to Response.End that requires observation
        private bool _flushing;
        private bool _clientDisconnected;
        private bool _filteringCompleted;
        private bool _closeConnectionAfterError;

        // simple properties

        private int         _statusCode = 200;
        private String      _statusDescription;
        private bool        _bufferOutput = true;
        private String      _contentType = "text/html";
        private String      _charSet;
        private bool        _customCharSet;
        private bool        _contentLengthSet;
        private String      _redirectLocation;
        private bool        _redirectLocationSet;
        private Encoding    _encoding;
        private Encoder     _encoder; // cached encoder for the encoding
        private Encoding    _headerEncoding; // encoding for response headers, default utf-8
        private bool        _cacheControlHeaderAdded;
        private HttpCachePolicy _cachePolicy;
        private ArrayList   _cacheHeaders;
        private bool        _suppressHeaders;
        private bool        _suppressContentSet;
        private bool        _suppressContent;
        private string      _appPathModifier;
        private bool        _isRequestBeingRedirected;
        private bool        _useAdaptiveError;
        private bool        _handlerHeadersGenerated;
        private bool        _sendCacheControlHeader;

        // complex properties

        private ArrayList               _customHeaders;
        private HttpCookieCollection    _cookies;
        #pragma warning disable 0649
        private ResponseDependencyList  _fileDependencyList;
        private ResponseDependencyList  _virtualPathDependencyList;
        private ResponseDependencyList  _cacheItemDependencyList;
        #pragma warning restore 0649
        private CacheDependency[]       _userAddedDependencies;
        private CacheDependency         _cacheDependencyForResponse;
        
        private ErrorFormatter          _overrideErrorFormatter;

        // cache properties
        int         _expiresInMinutes;
        bool        _expiresInMinutesSet;
        DateTime    _expiresAbsolute;
        bool        _expiresAbsoluteSet;
        string      _cacheControl;

        private bool        _statusSet;
        private int         _subStatusCode;
        private bool        _versionHeaderSent;

        // These flags for content-type are only used in integrated mode.
        // DevDivBugs 146983: Content-Type should not be sent when the resonse buffers are empty
        // DevDivBugs 195148: need to send Content-Type when the handler is managed and the response buffers are non-empty 
        // Dev10 750934: need to send Content-Type when explicitly set by managed caller
        private bool        _contentTypeSetByManagedCaller;
        private bool        _contentTypeSetByManagedHandler;

        // chunking
        bool        _transferEncodingSet;
        bool        _chunked;

        // OnSendingHeaders pseudo-event
        private SubscriptionQueue<Action<HttpContext>> _onSendingHeadersSubscriptionQueue = new SubscriptionQueue<Action<HttpContext>>();

        // mobile redirect properties
        internal static readonly String RedirectQueryStringVariable = "__redir";
        internal static readonly String RedirectQueryStringValue = "1";
        internal static readonly String RedirectQueryStringAssignment = RedirectQueryStringVariable + "=" + RedirectQueryStringValue;

        private static readonly String _redirectQueryString = "?" + RedirectQueryStringAssignment;
        private static readonly String _redirectQueryStringInline = RedirectQueryStringAssignment + "&";

        internal static event EventHandler Redirecting;

        internal HttpContext Context {
            get { return _context; }
            set { _context = value; }
        }

        internal HttpRequest Request {
            get {
                if (_context == null)
                    return null;
                return _context.Request;
            }
        }

        /*
         * Internal package visible constructor to create responses that
         * have HttpWorkerRequest
         *
         * @param wr Worker Request
         */
        internal HttpResponse(HttpWorkerRequest wr, HttpContext context) {
            _wr = wr;
            _context = context;
            // HttpWriter is created in InitResponseWriter
        }

        // Public constructor for responses that go to an arbitrary writer
        // Initializes a new instance of the <see langword='HttpResponse'/> class.</para>
        public HttpResponse(TextWriter writer) {
            _wr = null;
            _httpWriter = null;
            _writer = writer;
        }

        private bool UsingHttpWriter {
            get {
                return (_httpWriter != null && _writer == _httpWriter);
            }
        }

        internal void SetAllocatorProvider(IAllocatorProvider allocator) {
            if (_httpWriter != null) {
                _httpWriter.AllocatorProvider = allocator;
            }
        }

        /*
         *  Cleanup code
         */
        internal void Dispose() {
            // recycle buffers
            if (_httpWriter != null)
                _httpWriter.RecycleBuffers();
            // recycle dependencies
            if (_cacheDependencyForResponse != null) {
                _cacheDependencyForResponse.Dispose();
                _cacheDependencyForResponse = null;
            }
            if (_userAddedDependencies != null) {
                foreach (CacheDependency dep in _userAddedDependencies) {
                    dep.Dispose();
                }
                _userAddedDependencies = null;
            }
        }

        internal void InitResponseWriter() {
            if (_httpWriter == null) {
                _httpWriter = new HttpWriter(this);

                _writer = _httpWriter;
            }
        }

        //
        // Private helper methods
        //

        private void AppendHeader(HttpResponseHeader h) {
            if (_customHeaders == null)
                _customHeaders = new ArrayList();
            _customHeaders.Add(h);
            if (_cachePolicy != null && StringUtil.EqualsIgnoreCase("Set-Cookie", h.Name)) {
                _cachePolicy.SetHasSetCookieHeader();
            }
        }

        public bool HeadersWritten {
            get { return _headersWritten; }
            internal set { _headersWritten = value; }
        }

        internal ArrayList GenerateResponseHeadersIntegrated(bool forCache) {
            ArrayList headers = new ArrayList();
            HttpHeaderCollection responseHeaders = Headers as HttpHeaderCollection;
            int headerId = 0;

            // copy all current response headers
            foreach(String key in responseHeaders)
            {
                // skip certain headers that the cache does not cache
                // this is based on the cache headers saved separately in AppendHeader
                // and not generated in GenerateResponseHeaders in ISAPI mode
                headerId = HttpWorkerRequest.GetKnownResponseHeaderIndex(key);
                if (headerId >= 0 && forCache &&
                     (headerId == HttpWorkerRequest.HeaderServer ||
                      headerId == HttpWorkerRequest.HeaderSetCookie ||
                      headerId == HttpWorkerRequest.HeaderCacheControl ||
                      headerId == HttpWorkerRequest.HeaderExpires ||
                      headerId == HttpWorkerRequest.HeaderLastModified ||
                      headerId == HttpWorkerRequest.HeaderEtag ||
                      headerId == HttpWorkerRequest.HeaderVary)) {
                    continue;
                }

                if ( headerId >= 0 ) {
                    headers.Add(new HttpResponseHeader(headerId, responseHeaders[key]));
                }
                else {
                    headers.Add(new HttpResponseHeader(key, responseHeaders[key]));
                }
            }

            return headers;
        }

        internal void GenerateResponseHeadersForCookies()
        {
            if (_cookies == null || (_cookies.Count == 0 && !_cookies.Changed))
                return; // no cookies exist

            HttpHeaderCollection headers = Headers as HttpHeaderCollection;
            HttpResponseHeader cookieHeader = null;
            HttpCookie cookie = null;
            bool needToReset = false;

            // Go through all cookies, and check whether any have been added
            // or changed.  If a cookie was added, we can simply generate a new
            // set cookie header for it.  If the cookie collection has been
            // changed (cleared or cookies removed), or an existing cookie was
            // changed, we have to regenerate all Set-Cookie headers due to an IIS
            // limitation that prevents us from being able to delete specific
            // Set-Cookie headers for items that changed.
            if (!_cookies.Changed)
            {
                for(int c = 0; c < _cookies.Count; c++)
                {
                    cookie = _cookies[c];
                    if (cookie.Added) {
                        // if a cookie was added, we generate a Set-Cookie header for it
                        cookieHeader = cookie.GetSetCookieHeader(_context);
                        headers.SetHeader(cookieHeader.Name, cookieHeader.Value, false);
                        cookie.Added = false;
                        cookie.Changed = false;
                    }
                    else if (cookie.Changed) {
                        // if a cookie has changed, we need to clear all cookie
                        // headers and re-write them all since we cant delete
                        // specific existing cookies
                        needToReset = true;
                        break;
                    }
                }
            }


            if (_cookies.Changed || needToReset)
            {
                // delete all set cookie headers
                headers.Remove("Set-Cookie");

                // write all the cookies again
                for(int c = 0; c < _cookies.Count; c++)
                {
                    // generate a Set-Cookie header for each cookie
                    cookie = _cookies[c];
                    cookieHeader = cookie.GetSetCookieHeader(_context);
                    headers.SetHeader(cookieHeader.Name, cookieHeader.Value, false);
                    cookie.Added = false;
                    cookie.Changed = false;
                }

                _cookies.Changed = false;
            }
        }

        internal void GenerateResponseHeadersForHandler()
        {
            if ( !(_wr is IIS7WorkerRequest) ) {
                return;
            }

            String versionHeader = null;

            // Generate the default headers associated with an ASP.NET handler
            if (!_headersWritten && !_handlerHeadersGenerated) {
                try {
                    // The "sendCacheControlHeader" is default to true, but a false setting in either
                    // the <httpRuntime> section (legacy) or the <outputCache> section (current) will disable
                    // sending of that header.
                    RuntimeConfig config = RuntimeConfig.GetLKGConfig(_context);

                    HttpRuntimeSection runtimeConfig = config.HttpRuntime;
                    if (runtimeConfig != null) {
                        versionHeader = runtimeConfig.VersionHeader;
                        _sendCacheControlHeader = runtimeConfig.SendCacheControlHeader;
                    }

                    OutputCacheSection outputCacheConfig = config.OutputCache;
                    if (outputCacheConfig != null) {
                        _sendCacheControlHeader &= outputCacheConfig.SendCacheControlHeader;
                    }

                    // DevDiv #406078: Need programmatic way of disabling "Cache-Control: private" response header.
                    if (SuppressDefaultCacheControlHeader) {
                        _sendCacheControlHeader = false;
                    }

                    // Ensure that cacheability is set to cache-control: private
                    // if it is not explicitly set
                    if (_sendCacheControlHeader && !_cacheControlHeaderAdded) {
                        Headers.Set("Cache-Control", "private");
                    }

                    // set the version header
                    if (!String.IsNullOrEmpty(versionHeader)) {
                        Headers.Set("X-AspNet-Version", versionHeader);
                    }

                    // Force content-type generation
                    _contentTypeSetByManagedHandler = true;
                }
                finally {
                    _handlerHeadersGenerated = true;
                }
            }
        }

        internal ArrayList GenerateResponseHeaders(bool forCache) {
            ArrayList   headers = new ArrayList();
            bool sendCacheControlHeader = HttpRuntimeSection.DefaultSendCacheControlHeader;

            // ASP.NET version header
            if (!forCache ) {

                if (!_versionHeaderSent) {
                    String versionHeader = null;

                    // The "sendCacheControlHeader" is default to true, but a false setting in either
                    // the <httpRuntime> section (legacy) or the <outputCache> section (current) will disable
                    // sending of that header.
                    RuntimeConfig config = RuntimeConfig.GetLKGConfig(_context);

                    HttpRuntimeSection runtimeConfig = config.HttpRuntime;
                    if (runtimeConfig != null) {
                        versionHeader = runtimeConfig.VersionHeader;
                        sendCacheControlHeader = runtimeConfig.SendCacheControlHeader;
                    }

                    OutputCacheSection outputCacheConfig = config.OutputCache;
                    if (outputCacheConfig != null) {
                        sendCacheControlHeader &= outputCacheConfig.SendCacheControlHeader;
                    }

                    if (!String.IsNullOrEmpty(versionHeader)) {
                        headers.Add(new HttpResponseHeader("X-AspNet-Version", versionHeader));
                    }

                    _versionHeaderSent = true;
                }
            }

            // custom headers
            if (_customHeaders != null) {
                int numCustomHeaders = _customHeaders.Count;
                for (int i = 0; i < numCustomHeaders; i++)
                    headers.Add(_customHeaders[i]);
            }

            // location of redirect
            if (_redirectLocation != null) {
                headers.Add(new HttpResponseHeader(HttpWorkerRequest.HeaderLocation, _redirectLocation));
            }

            // don't include headers that the cache changes or omits on a cache hit
            if (!forCache) {
                // cookies
                if (_cookies != null) {
                    int numCookies = _cookies.Count;

                    for (int i = 0; i < numCookies; i++) {
                        headers.Add(_cookies[i].GetSetCookieHeader(Context));
                    }
                }

                // cache policy
                if (_cachePolicy != null && _cachePolicy.IsModified()) {
                    _cachePolicy.GetHeaders(headers, this);
                }
                else {
                    if (_cacheHeaders != null) {
                        headers.AddRange(_cacheHeaders);
                    }

                    /*
                     * Ensure that cacheability is set to cache-control: private
                     * if it is not explicitly set.
                     */
                    if (!_cacheControlHeaderAdded && sendCacheControlHeader) {
                        headers.Add(new HttpResponseHeader(HttpWorkerRequest.HeaderCacheControl, "private"));
                    }
                }
            }

            //
            // content type
            //
            if ( _statusCode != 204 && _contentType != null) {
                String contentType = AppendCharSetToContentType( _contentType );
                headers.Add(new HttpResponseHeader(HttpWorkerRequest.HeaderContentType, contentType));
            }

            // done
            return headers;
        }

        internal string AppendCharSetToContentType(string contentType)
        {
            String newContentType = contentType;

            // charset=xxx logic -- append if
            //      not there already and
            //          custom set or response encoding used by http writer to convert bytes to chars
            if (_customCharSet || (_httpWriter != null && _httpWriter.ResponseEncodingUsed)) {
                if (contentType.IndexOf("charset=", StringComparison.Ordinal) < 0) {
                    String charset = Charset;
                    if (charset.Length > 0) { // not suppressed
                        newContentType = contentType + "; charset=" + charset;
                    }
                }
            }

            return newContentType;
        }

        internal bool UseAdaptiveError {
            get {
                return _useAdaptiveError;
            }
            set {
                _useAdaptiveError = value;
            }
        }

        private void WriteHeaders() {
            if (_wr == null)
                return;

             // Fire pre-send headers event

            if (_context != null && _context.ApplicationInstance != null) {
                _context.ApplicationInstance.RaiseOnPreSendRequestHeaders();
            }

            // status
            // VSWhidbey 270635: We need to reset the status code for mobile devices.
            if (UseAdaptiveError) {

                // VSWhidbey 288054: We should change the status code for cases
                // that cannot be handled by mobile devices
                // 4xx for Client Error and 5xx for Server Error in HTTP spec
                int statusCode = StatusCode;
                if (statusCode >= 400 && statusCode < 600) {
                    this.StatusCode = 200;
                }
            }

            // generate headers before we touch the WorkerRequest since header generation might fail,
            // and we don't want to have touched the WR if this happens
            ArrayList headers = GenerateResponseHeaders(false);

            _wr.SendStatus(this.StatusCode, this.StatusDescription);

            // headers encoding

            // unicode messes up the response badly
            Debug.Assert(!this.HeaderEncoding.Equals(Encoding.Unicode));
            _wr.SetHeaderEncoding(this.HeaderEncoding);

            // headers
            HttpResponseHeader header = null;
            int n = (headers != null) ? headers.Count : 0;
            for (int i = 0; i < n; i++)
            {
                header = headers[i] as HttpResponseHeader;
                header.Send(_wr);
            }
        }

        internal int GetBufferedLength() {
            // if length is greater than Int32.MaxValue, Convert.ToInt32 will throw.
            // This is okay until we support large response sizes
            return (_httpWriter != null) ? Convert.ToInt32(_httpWriter.GetBufferedLength()) : 0;
        }

        private static byte[] s_chunkSuffix = new byte[2] { (byte)'\r', (byte)'\n'};
        private static byte[] s_chunkEnd    = new byte[5] { (byte)'0',  (byte)'\r', (byte)'\n', (byte)'\r', (byte)'\n'};

        private void Flush(bool finalFlush, bool async = false) {
            // Already completed or inside Flush?
            if (_completed || _flushing)
                return;

            // Special case for non HTTP Writer
            if (_httpWriter == null) {
                _writer.Flush();
                return;
            }

            // Avoid recursive flushes
            _flushing = true;

            bool needToClearBuffers = false;
            try {

                IIS7WorkerRequest iis7WorkerRequest = _wr as IIS7WorkerRequest;
                if (iis7WorkerRequest != null) {
                    // generate the handler headers if flushing
                    GenerateResponseHeadersForHandler();

                    // Push buffers across to native side and explicitly flush.
                    // IIS7 handles the chunking as necessary so we can omit that logic
                    UpdateNativeResponse(true /*sendHeaders*/);
                    
                    if (!async) {
                        try {
                            // force a synchronous send
                            iis7WorkerRequest.ExplicitFlush();
                        }
                        finally {
                            // always set after flush, successful or not
                            _headersWritten = true;
                        }
                    }

                    return;
                }

                long bufferedLength = 0;

                //
                // Headers
                //

                if (!_headersWritten) {
                    if (!_suppressHeaders && !_clientDisconnected) {
                        EnsureSessionStateIfNecessary();

                        if (finalFlush) {
                            bufferedLength = _httpWriter.GetBufferedLength();

                            // suppress content-type for empty responses
                            if (!_contentLengthSet && bufferedLength == 0 && _httpWriter != null)
                                _contentType = null;

                            SuppressCachingCookiesIfNecessary();

                            // generate response headers
                            WriteHeaders();

                            // recalculate as sending headers might change it (PreSendHeaders)
                            bufferedLength = _httpWriter.GetBufferedLength();

                            // Calculate content-length if not set explicitely
                            // WOS #1380818: Content-Length should not be set for response with 304 status (HTTP.SYS doesn't, and HTTP 1.1 spec implies it)
                            if (!_contentLengthSet && _statusCode != 304)
                                _wr.SendCalculatedContentLength(bufferedLength);
                        }
                        else {
                            // Check if need chunking for HTTP/1.1
                            if (!_contentLengthSet && !_transferEncodingSet && _statusCode == 200) {
                                String protocol = _wr.GetHttpVersion();

                                if (protocol != null && protocol.Equals("HTTP/1.1")) {
                                    AppendHeader(new HttpResponseHeader(HttpWorkerRequest.HeaderTransferEncoding, "chunked"));
                                    _chunked = true;
                                }

                                bufferedLength = _httpWriter.GetBufferedLength();
                            }

                            WriteHeaders();
                        }
                    }

                    _headersWritten = true;
                }
                else {
                    bufferedLength = _httpWriter.GetBufferedLength();
                }

                //
                // Filter and recalculate length if not done already
                //

                if (!_filteringCompleted) {
                    _httpWriter.Filter(false);
                    bufferedLength = _httpWriter.GetBufferedLength();
                }

                //
                // Content
                //

                // suppress HEAD content unless overriden
                if (!_suppressContentSet && Request != null && Request.HttpVerb == HttpVerb.HEAD)
                    _suppressContent = true;

                if (_suppressContent || _ended) {
                    _httpWriter.ClearBuffers();
                    bufferedLength = 0;
                }

                if (!_clientDisconnected) {
                    // Fire pre-send request event
                    if (_context != null && _context.ApplicationInstance != null)
                        _context.ApplicationInstance.RaiseOnPreSendRequestContent();

                    if (_chunked) {
                        if (bufferedLength > 0) {
                            byte[] chunkPrefix = Encoding.ASCII.GetBytes(Convert.ToString(bufferedLength, 16) + "\r\n");
                            _wr.SendResponseFromMemory(chunkPrefix, chunkPrefix.Length);

                            _httpWriter.Send(_wr);

                            _wr.SendResponseFromMemory(s_chunkSuffix, s_chunkSuffix.Length);
                        }

                        if (finalFlush)
                            _wr.SendResponseFromMemory(s_chunkEnd, s_chunkEnd.Length);
                    }
                    else {
                        _httpWriter.Send(_wr);
                    }
                    
                    if (!async) {
                        needToClearBuffers = !finalFlush;
                        _wr.FlushResponse(finalFlush);
                    }
                    _wr.UpdateResponseCounters(finalFlush, (int)bufferedLength);
                }
            }
            finally {
                _flushing = false;

                // Remember if completed
                if (finalFlush && _headersWritten)
                    _completed = true;

                // clear buffers even if FlushResponse throws
                if (needToClearBuffers)
                    _httpWriter.ClearBuffers();
            }
        }

        internal void FinalFlushAtTheEndOfRequestProcessing() {
            FinalFlushAtTheEndOfRequestProcessing(false);
        }

        internal void FinalFlushAtTheEndOfRequestProcessing(bool needPipelineCompletion) {
                Flush(true);
        }

        // Returns true if the HttpWorkerRequest supports asynchronous flush; otherwise false.
        public bool SupportsAsyncFlush {
            get {
                return (_wr != null && _wr.SupportsAsyncFlush);
            }
        }

        // Sends the currently buffered response to the client.  If the underlying HttpWorkerRequest
        // supports asynchronous flush and this method is called from an asynchronous module event
        // or asynchronous handler, then the send will be performed asynchronously.  Otherwise the
        // implementation resorts to a synchronous flush.  The HttpResponse.SupportsAsyncFlush property 
        // returns the value of HttpWorkerRequest.SupportsAsyncFlush.  Asynchronous flush is supported
        // for IIS 6.0 and higher.
        public IAsyncResult BeginFlush(AsyncCallback callback, Object state) {
            if (_completed)
                throw new HttpException(SR.GetString(SR.Cannot_flush_completed_response));

            // perform async flush if it is supported
            if (_wr != null && _wr.SupportsAsyncFlush && !_context.IsInCancellablePeriod) {
                Flush(false, true);
                return _wr.BeginFlush(callback, state);
            }

            // perform a [....] flush since async is not supported
            FlushAsyncResult ar = new FlushAsyncResult(callback, state);
            try {
                Flush(false);
            }
            catch(Exception e) {
                ar.SetError(e);
            }
            ar.Complete(0, HResults.S_OK, IntPtr.Zero, synchronous: true);
            return ar;
        }

        // Finish an asynchronous flush.
        public void EndFlush(IAsyncResult asyncResult) {
            // finish async flush if it is supported
            if (_wr != null && _wr.SupportsAsyncFlush && !_context.IsInCancellablePeriod) {
                // integrated mode doesn't set this until after ExplicitFlush is called,
                // but classic mode sets it after WriteHeaders is called
                _headersWritten = true;
                if (!(_wr is IIS7WorkerRequest)) {
                    _httpWriter.ClearBuffers();
                }
                _wr.EndFlush(asyncResult);
                return;
            }
            
            // finish [....] flush since async is not supported
            if (asyncResult == null)
                throw new ArgumentNullException("asyncResult");
            FlushAsyncResult ar = asyncResult as FlushAsyncResult;
            if (ar == null)
                throw new ArgumentException(null, "asyncResult");
            ar.ReleaseWaitHandleWhenSignaled();
            if (ar.Error != null) {
                ar.Error.Throw();
            }
        }

        public Task FlushAsync() {
            return Task.Factory.FromAsync(BeginFlush, EndFlush, state: null);
        }

        // WOS 1555777: kernel cache support
        // If the response can be kernel cached, return the kernel cache key;
        // otherwise return null.  The kernel cache key is used to invalidate
        // the entry if a dependency changes or the item is flushed from the
        // managed cache for any reason.
        internal String SetupKernelCaching(String originalCacheUrl) {
            // don't kernel cache if we have a cookie header
            if (_cookies != null && _cookies.Count != 0) {
                _cachePolicy.SetHasSetCookieHeader();
                return null;
            }

            bool enableKernelCacheForVaryByStar = IsKernelCacheEnabledForVaryByStar();

            // check cache policy
            if (!_cachePolicy.IsKernelCacheable(Request, enableKernelCacheForVaryByStar)) {
                return null;
            }

            // check configuration if the kernel mode cache is enabled
            HttpRuntimeSection runtimeConfig = RuntimeConfig.GetLKGConfig(_context).HttpRuntime;
            if (runtimeConfig == null || !runtimeConfig.EnableKernelOutputCache) {
                return null;
            }

            double seconds = (_cachePolicy.UtcGetAbsoluteExpiration() - DateTime.UtcNow).TotalSeconds;
            if (seconds <= 0) {
                return null;
            }

            int secondsToLive = seconds < Int32.MaxValue ? (int) seconds : Int32.MaxValue;
            string kernelCacheUrl = _wr.SetupKernelCaching(secondsToLive, originalCacheUrl, enableKernelCacheForVaryByStar);

            if (kernelCacheUrl != null) {
                // Tell cache policy not to use max-age as kernel mode cache doesn't update it
                _cachePolicy.SetNoMaxAgeInCacheControl();
            }

            return kernelCacheUrl;
        }

        /*
         * Disable kernel caching for this response.  If kernel caching is not supported, this method
         * returns without performing any action.
         */
        public void DisableKernelCache() {
            if (_wr == null) {
                return;
            }

            _wr.DisableKernelCache();
        }

        /*
         * Disable IIS user-mode caching for this response.  If IIS user-mode caching is not supported, this method
         * returns without performing any action.
         */
        public void DisableUserCache() {
            if (_wr == null) {
                return;
            }

            _wr.DisableUserCache();
        }

        private bool IsKernelCacheEnabledForVaryByStar()
        {
            OutputCacheSection outputCacheConfig = RuntimeConfig.GetAppConfig().OutputCache;
            return (_cachePolicy.IsVaryByStar && outputCacheConfig.EnableKernelCacheForVaryByStar);
        }

        internal void FilterOutput() {
            if(_filteringCompleted) {
                return;
            }

            try {
                if (UsingHttpWriter) {
                    IIS7WorkerRequest iis7WorkerRequest = _wr as IIS7WorkerRequest;
                    if (iis7WorkerRequest != null) {
                        _httpWriter.FilterIntegrated(true, iis7WorkerRequest);
                    }
                    else {
                        _httpWriter.Filter(true);
                    }
                }
            }
            finally {
                _filteringCompleted = true;
            }
        }

        /// <devdoc>
        /// Prevents any other writes to the Response
        /// </devdoc>
        internal void IgnoreFurtherWrites() {
            if (UsingHttpWriter) {
                _httpWriter.IgnoreFurtherWrites();
            }
        }

        /*
         * Is the entire response buffered so far
         */
        internal bool IsBuffered() {
            return !_headersWritten && UsingHttpWriter;
        }

        //  Expose cookie collection to request
        //    Gets the HttpCookie collection sent by the current request.</para>
        public HttpCookieCollection Cookies {
            get {
                if (_cookies == null)
                    _cookies = new HttpCookieCollection(this, false);

                return _cookies;
            }
        }

        // returns TRUE iff there is at least one response cookie marked Shareable = false
        internal bool ContainsNonShareableCookies() {
            if (_cookies != null) {
                for (int i = 0; i < _cookies.Count; i++) {
                    if (!_cookies[i].Shareable) {
                        return true;
                    }
                }
            }
            return false;
        }

        internal HttpCookieCollection GetCookiesNoCreate() {
            return _cookies;
        }

        public NameValueCollection Headers {
            get {
                if ( !(_wr is IIS7WorkerRequest) ) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }

                if (_headers == null) {
                    _headers = new HttpHeaderCollection(_wr, this, 16);
                }

                return _headers;
            }
        }

        /*
         * Add dependency on a file to the current response
         */

        /// <devdoc>
        ///    <para>Adds dependency on a file to the current response.</para>
        /// </devdoc>
        public void AddFileDependency(String filename) {
            _fileDependencyList.AddDependency(filename, "filename");
        }

        // Add dependency on a list of files to the current response

        //   Adds dependency on a group of files to the current response.
        public void AddFileDependencies(ArrayList filenames) {
            _fileDependencyList.AddDependencies(filenames, "filenames");
        }


        public void AddFileDependencies(string[] filenames) {
            _fileDependencyList.AddDependencies(filenames, "filenames");
        }

        internal void AddVirtualPathDependencies(string[] virtualPaths) {
            _virtualPathDependencyList.AddDependencies(virtualPaths, "virtualPaths", false, Request.Path);
        }

        internal void AddFileDependencies(string[] filenames, DateTime utcTime) {
            _fileDependencyList.AddDependencies(filenames, "filenames", false, utcTime);
        }

        // Add dependency on another cache item to the response.
        public void AddCacheItemDependency(string cacheKey) {
            _cacheItemDependencyList.AddDependency(cacheKey, "cacheKey");
        }

        // Add dependency on a list of cache items to the response.
        public void AddCacheItemDependencies(ArrayList cacheKeys) {
            _cacheItemDependencyList.AddDependencies(cacheKeys, "cacheKeys");
        }


        public void AddCacheItemDependencies(string[] cacheKeys) {
            _cacheItemDependencyList.AddDependencies(cacheKeys, "cacheKeys");
        }

        // Add dependency on one or more CacheDependency objects to the response
        public void AddCacheDependency(params CacheDependency[] dependencies) {
            if (dependencies == null) {
                throw new ArgumentNullException("dependencies");
            }
            if (dependencies.Length == 0) {
                return;
            }
            if (_cacheDependencyForResponse != null) {
                throw new InvalidOperationException(SR.GetString(SR.Invalid_operation_cache_dependency));
            }
            if (_userAddedDependencies == null) {
                // copy array argument contents so they can't be changed beneath us
                _userAddedDependencies = (CacheDependency[]) dependencies.Clone();
            }
            else {
                CacheDependency[] deps = new CacheDependency[_userAddedDependencies.Length + dependencies.Length];
                int i = 0;
                for (i = 0; i < _userAddedDependencies.Length; i++) {
                    deps[i] = _userAddedDependencies[i];
                }
                for (int j = 0; j < dependencies.Length; j++) {
                    deps[i + j] = dependencies[j];
                }
                _userAddedDependencies = deps;
            }
            Cache.SetDependencies(true);
        }

        public static void RemoveOutputCacheItem(string path) {
            RemoveOutputCacheItem(path, null);
        }

        public static void RemoveOutputCacheItem(string path, string providerName) {
            if (path == null)
                throw new ArgumentNullException("path");
            if (StringUtil.StringStartsWith(path, "\\\\") || path.IndexOf(':') >= 0 || !UrlPath.IsRooted(path))
                throw new ArgumentException(SR.GetString(SR.Invalid_path_for_remove, path));

            string key = OutputCacheModule.CreateOutputCachedItemKey(
                    path, HttpVerb.GET, null, null);

            if (providerName == null) {
                OutputCache.Remove(key, (HttpContext)null);
            }
            else {
                OutputCache.RemoveFromProvider(key, providerName);
            }

            key = OutputCacheModule.CreateOutputCachedItemKey(
                    path, HttpVerb.POST, null, null);
            
            if (providerName == null) {
                OutputCache.Remove(key, (HttpContext)null);
            }
            else { 
                OutputCache.RemoveFromProvider(key, providerName);
            }
        }

        // Check if there are file dependencies.
        internal bool HasFileDependencies() {
            return _fileDependencyList.HasDependencies();
        }

        // Check if there are item dependencies.
        internal bool HasCacheItemDependencies() {
            return _cacheItemDependencyList.HasDependencies();
        }

        internal CacheDependency CreateCacheDependencyForResponse() {
            if (_cacheDependencyForResponse == null) {
                CacheDependency dependency;
                
                // N.B. - add file dependencies last so that we hit the file changes monitor
                // just once.
                dependency = _cacheItemDependencyList.CreateCacheDependency(CacheDependencyType.CacheItems, null);
                dependency = _fileDependencyList.CreateCacheDependency(CacheDependencyType.Files, dependency);
                dependency = _virtualPathDependencyList.CreateCacheDependency(CacheDependencyType.VirtualPaths, dependency);
                
                // N.B. we add in the aggregate dependency here, and return it,
                // so this function should only be called once, because the resulting
                // dependency can only be added to the cache once
                if (_userAddedDependencies != null) {
                    AggregateCacheDependency agg = new AggregateCacheDependency();
                    agg.Add(_userAddedDependencies);
                    if (dependency != null) {
                        agg.Add(dependency);
                    }
                    // clear it because we added them to the dependencies for the response
                    _userAddedDependencies = null;
                    _cacheDependencyForResponse = agg;
                }
                else {
                    _cacheDependencyForResponse = dependency;
                }
            }
            return _cacheDependencyForResponse;
        }

        // Get response headers and content as HttpRawResponse
        internal HttpRawResponse GetSnapshot() {
            int statusCode = 200;
            string statusDescription = null;
            ArrayList headers = null;
            ArrayList buffers = null;
            bool hasSubstBlocks = false;

            if (!IsBuffered())
                throw new HttpException(SR.GetString(SR.Cannot_get_snapshot_if_not_buffered));

            IIS7WorkerRequest iis7WorkerRequest = _wr as IIS7WorkerRequest;

            // data
            if (!_suppressContent) {
                if (iis7WorkerRequest != null) {
                    buffers = _httpWriter.GetIntegratedSnapshot(out hasSubstBlocks, iis7WorkerRequest);
                }
                else {
                    buffers = _httpWriter.GetSnapshot(out hasSubstBlocks);
                }
            }

            // headers (after data as the data has side effects (like charset, see ASURT 113202))
            if (!_suppressHeaders) {
                statusCode = _statusCode;
                statusDescription = _statusDescription;
                // In integrated pipeline, we need to use the current response headers
                // from the response (these may have been generated by other handlers, etc)
                // instead of the ASP.NET cached headers
                if (iis7WorkerRequest != null) {
                    headers = GenerateResponseHeadersIntegrated(true);
                }
                else {
                    headers = GenerateResponseHeaders(true);
                }
            }
            return new HttpRawResponse(statusCode, statusDescription, headers, buffers, hasSubstBlocks);
        }

        // Send saved response snapshot as the entire response
        internal void UseSnapshot(HttpRawResponse rawResponse, bool sendBody) {
            if (_headersWritten)
                throw new HttpException(SR.GetString(SR.Cannot_use_snapshot_after_headers_sent));

            if (_httpWriter == null)
                throw new HttpException(SR.GetString(SR.Cannot_use_snapshot_for_TextWriter));

            ClearAll();

            // restore status
            StatusCode = rawResponse.StatusCode;
            StatusDescription = rawResponse.StatusDescription;

            // restore headers
            ArrayList headers = rawResponse.Headers;
            int n = (headers != null) ? headers.Count : 0;
            for (int i = 0; i < n; i++) {
                HttpResponseHeader h = (HttpResponseHeader)(headers[i]);
                this.AppendHeader(h.Name, h.Value);
            }

            // restore content
            _httpWriter.UseSnapshot(rawResponse.Buffers);

            _suppressContent = !sendBody;
        }

        internal void CloseConnectionAfterError() {
            _closeConnectionAfterError = true;
        }

        private void WriteErrorMessage(Exception e, bool dontShowSensitiveErrors) {
            ErrorFormatter errorFormatter = null;
            CultureInfo uiculture = null, savedUiculture = null;
            bool needToRestoreUiculture = false;

            if (_context.DynamicUICulture != null) {
                // if the user set the culture dynamically use it
                uiculture =  _context.DynamicUICulture;
            }
            else  {
                // get the UI culture under which the error text must be created (use LKG to avoid errors while reporting error)
                GlobalizationSection globConfig = RuntimeConfig.GetLKGConfig(_context).Globalization;
                if ((globConfig != null) && (!String.IsNullOrEmpty(globConfig.UICulture))) {
                    try {
                        uiculture = HttpServerUtility.CreateReadOnlyCultureInfo(globConfig.UICulture);
                    }
                    catch {
                    }
                }
            }

            //  In Integrated mode, generate the necessary response headers for the error
            GenerateResponseHeadersForHandler();

            // set the UI culture
            if (uiculture != null) {
                savedUiculture = Thread.CurrentThread.CurrentUICulture;
                Thread.CurrentThread.CurrentUICulture = uiculture;
                needToRestoreUiculture = true;
            }

            try {
                try {
                    // Try to get an error formatter
                    errorFormatter = GetErrorFormatter(e);
#if DBG
                    Debug.Trace("internal", "Error stack for " + Request.Path, e);
#endif
                    if (dontShowSensitiveErrors && !errorFormatter.CanBeShownToAllUsers)
                        errorFormatter = new GenericApplicationErrorFormatter(Request.IsLocal);

                    Debug.Trace("internal", "errorFormatter's type = " +  errorFormatter.GetType());

                    if (ErrorFormatter.RequiresAdaptiveErrorReporting(Context)) {
                        _writer.Write(errorFormatter.GetAdaptiveErrorMessage(Context, dontShowSensitiveErrors));
                    }
                    else {
                        _writer.Write(errorFormatter.GetHtmlErrorMessage(dontShowSensitiveErrors));

                        // Write a stack dump in an HTML comment for debugging purposes
                        // Only show it for Asp permission medium or higher (ASURT 126373)
                        if (!dontShowSensitiveErrors &&
                            HttpRuntime.HasAspNetHostingPermission(AspNetHostingPermissionLevel.Medium)) {
                            _writer.Write("<!-- \r\n");
                            WriteExceptionStack(e);
                            _writer.Write("-->");
                        }
                         if (!dontShowSensitiveErrors && !Request.IsLocal ) {
                             _writer.Write("<!-- \r\n");
                             _writer.Write(SR.GetString(SR.Information_Disclosure_Warning));
                             _writer.Write("-->");
                         }
                    }

                    if (_closeConnectionAfterError) {
                        Flush();
                        Close();
                    }
                }
                finally {
                    // restore ui culture
                    if (needToRestoreUiculture)
                        Thread.CurrentThread.CurrentUICulture = savedUiculture;
                }
            }
            catch { // Protect against exception filters
                throw;
            }
        }

        internal void SetOverrideErrorFormatter(ErrorFormatter errorFormatter) {
            _overrideErrorFormatter = errorFormatter;
        }

        internal ErrorFormatter GetErrorFormatter(Exception e) {
            ErrorFormatter  errorFormatter = null;

            if (_overrideErrorFormatter != null) {
                return _overrideErrorFormatter;
            }

            // Try to get an error formatter
            errorFormatter = HttpException.GetErrorFormatter(e);

            if (errorFormatter == null) {
                ConfigurationException ce = e as ConfigurationException;
                if (ce != null && !String.IsNullOrEmpty(ce.Filename))
                    errorFormatter = new ConfigErrorFormatter(ce);
            }

            // If we couldn't get one, create one here
            if (errorFormatter == null) {
                // If it's a 404, use a special error page, otherwise, use a more
                // generic one.
                if (_statusCode == 404)
                    errorFormatter = new PageNotFoundErrorFormatter(Request.Path);
                else if (_statusCode == 403)
                    errorFormatter = new PageForbiddenErrorFormatter(Request.Path);
                else {
                    if (e is System.Security.SecurityException)
                        errorFormatter = new SecurityErrorFormatter(e);
                    else
                        errorFormatter = new UnhandledErrorFormatter(e);
                }
            }

            // Show config source only on local request for security reasons
            // Config file snippet may unintentionally reveal sensitive information (not related to the error)
            ConfigErrorFormatter configErrorFormatter = errorFormatter as ConfigErrorFormatter;
            if (configErrorFormatter != null) {
                configErrorFormatter.AllowSourceCode = Request.IsLocal;
            }

            return errorFormatter;
        }

        private void WriteOneExceptionStack(Exception e) {
            Exception subExcep = e.InnerException;
            if (subExcep != null)
                WriteOneExceptionStack(subExcep);

            string title = "[" + e.GetType().Name + "]";
            if (e.Message != null && e.Message.Length > 0)
                title += ": " + HttpUtility.HtmlEncode(e.Message);

            _writer.WriteLine(title);
            if (e.StackTrace != null)
                _writer.WriteLine(e.StackTrace);
        }

        private void WriteExceptionStack(Exception e) {
            ConfigurationErrorsException errors = e as ConfigurationErrorsException;
            if (errors == null) {
                WriteOneExceptionStack(e);
            }
            else {
                // Write the original exception to get the first error with
                // a full stack trace
                WriteOneExceptionStack(e);

                // Write additional errors, which will contain truncated stacks
                ICollection col = errors.Errors;
                if (col.Count > 1) {
                    bool firstSkipped = false;
                    foreach (ConfigurationException ce in col) {
                        if (!firstSkipped) {
                            firstSkipped = true;
                            continue;
                        }

                        _writer.WriteLine("---");
                        WriteOneExceptionStack(ce);
                    }
                }
            }
        }

        internal void ReportRuntimeError(Exception e, bool canThrow, bool localExecute) {
            CustomErrorsSection customErrorsSetting = null;
            bool useCustomErrors = false;
            int code = -1;

            if (_completed)
                return;

            // always try to disable IIS custom errors when we send an error
            if (_wr != null) {
                _wr.TrySkipIisCustomErrors = true;
            }

            if (!localExecute) {
                code = HttpException.GetHttpCodeForException(e);

                // Don't raise event for 404.  See VSWhidbey 124147.
                if (code != 404) {
                    WebBaseEvent.RaiseRuntimeError(e, this);
                }

                // This cannot use the HttpContext.IsCustomErrorEnabled property, since it must call
                // GetSettings() with the canThrow parameter.
                customErrorsSetting = CustomErrorsSection.GetSettings(_context, canThrow);
                if (customErrorsSetting != null)
                    useCustomErrors = customErrorsSetting.CustomErrorsEnabled(Request);
                else
                    useCustomErrors = true;
            }

            if (!_headersWritten) {
                // nothing sent yet - entire response

                if (code == -1) {
                    code = HttpException.GetHttpCodeForException(e);
                }

                // change 401 to 500 in case the config is not to impersonate
                if (code == 401 && !_context.IsClientImpersonationConfigured)
                    code = 500;

                if (_context.TraceIsEnabled)
                    _context.Trace.StatusCode = code;

                if (!localExecute && useCustomErrors) {
                    String redirect = (customErrorsSetting != null) ? customErrorsSetting.GetRedirectString(code) : null;

                    RedirectToErrorPageStatus redirectStatus = RedirectToErrorPage(redirect, customErrorsSetting.RedirectMode);
                    switch (redirectStatus) {
                        case RedirectToErrorPageStatus.Success:
                            // success - nothing to do
                            break;

                        case RedirectToErrorPageStatus.NotAttempted:
                            // if no redirect display generic error
                            ClearAll();
                            StatusCode = code;
                            WriteErrorMessage(e, dontShowSensitiveErrors: true);
                            break;

                        default:
                            // DevDiv #70492 - If we tried to display the custom error page but failed in doing so, we should display
                            // a generic error message instead of trying to display the original error. We have a compat switch on
                            // the <customErrors> element to control this behavior.

                            if (customErrorsSetting.AllowNestedErrors) {
                                // The user has set the compat switch to use the original (pre-bug fix) behavior.
                                goto case RedirectToErrorPageStatus.NotAttempted;
                            }

                            ClearAll();
                            StatusCode = 500;
                            HttpException dummyException = new HttpException();
                            dummyException.SetFormatter(new CustomErrorFailedErrorFormatter());
                            WriteErrorMessage(dummyException, dontShowSensitiveErrors: true);
                            break;
                    }
                }
                else {
                    ClearAll();
                    StatusCode = code;
                    WriteErrorMessage(e, dontShowSensitiveErrors: false);
                }
            }
            else {
                Clear();

                if (_contentType != null && _contentType.Equals("text/html")) {
                    // in the middle of Html - break Html
                    Write("\r\n\r\n</pre></table></table></table></table></table>");
                    Write("</font></font></font></font></font>");
                    Write("</i></i></i></i></i></b></b></b></b></b></u></u></u></u></u>");
                    Write("<p>&nbsp;</p><hr>\r\n\r\n");
                }

                WriteErrorMessage(e, useCustomErrors);
            }
        }

        internal void SynchronizeStatus(int statusCode, int subStatusCode, string description) {
            _statusCode = statusCode;
            _subStatusCode = subStatusCode;
            _statusDescription = description;
        }


        internal void SynchronizeHeader(int knownHeaderIndex, string name, string value) {
            HttpHeaderCollection headers = Headers as HttpHeaderCollection;
            headers.SynchronizeHeader(name, value);

            // unknown headers have an index < 0
            if (knownHeaderIndex < 0) {
                return;
            }

            bool fHeadersWritten = HeadersWritten;
            HeadersWritten = false; // Turn off the warning for "Headers have been written and can not be set"
            try {
                switch (knownHeaderIndex) {
                case HttpWorkerRequest.HeaderCacheControl:
                    _cacheControlHeaderAdded = true;
                    break;
                case HttpWorkerRequest.HeaderContentType:
                    _contentType = value;
                    break;
                case HttpWorkerRequest.HeaderLocation:
                    _redirectLocation = value;
                    _redirectLocationSet = false;
                    break;
                case HttpWorkerRequest.HeaderSetCookie:
                    // If the header is Set-Cookie, update the corresponding
                    // cookie in the cookies collection
                    if (value != null) {
                        HttpCookie cookie = HttpRequest.CreateCookieFromString(value);
                        // do not write this cookie back to IIS
                        cookie.FromHeader = true;
                        Cookies.Set(cookie);
                        cookie.Changed = false;
                        cookie.Added = false;
                    }
                    break;
                }
            } finally {
                HeadersWritten = fHeadersWritten;
            }
        }

        internal void SyncStatusIntegrated() {
            Debug.Assert(_wr is IIS7WorkerRequest, "_wr is IIS7WorkerRequest");
             if (!_headersWritten && _statusSet) {
                 // For integrated pipeline, synchronize the status immediately so that the FREB log
                 // correctly indicates the module and notification that changed the status.
                 _wr.SendStatus(_statusCode, _subStatusCode, this.StatusDescription);
                 _statusSet = false;
             }
        }

        // Public properties

        // Http status code
        //    Gets or sets the HTTP status code of output returned to client.
        public int StatusCode {
            get {
                return _statusCode;
            }

            set {
                if (_headersWritten)
                    throw new HttpException(SR.GetString(SR.Cannot_set_status_after_headers_sent));

                if (_statusCode != value) {
                    _statusCode = value;
                    _subStatusCode = 0;
                    _statusDescription = null;
                    _statusSet = true;
                }
            }
        }

        // the IIS sub status code
        // since this doesn't get emitted in the protocol
        // we won't send it through the worker request interface
        // directly
        public int SubStatusCode {
            get {
                if ( !(_wr is IIS7WorkerRequest) ) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }

                return _subStatusCode;
            }
            set {
                if ( !(_wr is IIS7WorkerRequest) ) {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
                }

                if (_headersWritten) {
                    throw new HttpException(SR.GetString(SR.Cannot_set_status_after_headers_sent));
                }

                _subStatusCode = value;
                _statusSet = true;
            }
        }

        // Allows setting both the status and the substatus individually. If not in IIS7 integrated mode,
        // the substatus code is ignored so as not to throw an exception.
        internal void SetStatusCode(int statusCode, int subStatus = -1) {
            StatusCode = statusCode;
            if (subStatus >= 0 && _wr is IIS7WorkerRequest) {
                SubStatusCode = subStatus;
            }
        }

        /*
         * Http status description string
         */

        // Http status description string
        //    Gets or sets the HTTP status string of output returned to the client.
        public String StatusDescription {
            get {
                if (_statusDescription == null)
                    _statusDescription = HttpWorkerRequest.GetStatusDescription(_statusCode);

                return _statusDescription;
            }

            set {
                if (_headersWritten)
                    throw new HttpException(SR.GetString(SR.Cannot_set_status_after_headers_sent));

                if (value != null && value.Length > 512)  // ASURT 124743
                    throw new ArgumentOutOfRangeException("value");
                _statusDescription = value;
                _statusSet = true;
            }
        }

        public bool TrySkipIisCustomErrors {
            get {
                if (_wr != null) {
                    return _wr.TrySkipIisCustomErrors;
                }
                return false;
            }
            set {
                if (_wr != null) {
                    _wr.TrySkipIisCustomErrors = value;
                }
            }
        }

        /// <summary>
        /// By default, the FormsAuthenticationModule hooks EndRequest and converts HTTP 401 status codes to
        /// HTTP 302, redirecting to the login page. This isn't appropriate for certain classes of errors,
        /// e.g. where authentication succeeded but authorization failed, or where the current request is
        /// an AJAX or web service request. This property provides a way to suppress the redirect behavior
        /// and send the original status code to the client.
        /// </summary>
        public bool SuppressFormsAuthenticationRedirect {
            get;
            set;
        }

        /// <summary>
        /// By default, ASP.NET sends a "Cache-Control: private" response header unless an explicit cache
        /// policy has been specified for this response. This property allows suppressing this default
        /// response header on a per-request basis. It can still be suppressed for the entire application
        /// by setting the appropriate value in &lt;httpRuntime&gt; or &lt;outputCache&gt;. See
        /// http://msdn.microsoft.com/en-us/library/system.web.configuration.httpruntimesection.sendcachecontrolheader.aspx
        /// for more information on those config elements.
        /// </summary>
        /// <remarks>
        /// Developers should use caution when suppressing the default Cache-Control header, as proxies
        /// and other intermediaries may treat responses without this header as cacheable by default.
        /// This could lead to the inadvertent caching of sensitive information.
        /// See RFC 2616, Sec. 13.4, for more information.
        /// </remarks>
        public bool SuppressDefaultCacheControlHeader {
            get;
            set;
        }

        // Flag indicating to buffer the output
        //    Gets or sets a value indicating whether HTTP output is buffered.
        public bool BufferOutput {
            get {
                return _bufferOutput;
            }

            set {
                if (_bufferOutput != value) {
                    _bufferOutput = value;

                    if (_httpWriter != null)
                        _httpWriter.UpdateResponseBuffering();
                }
            }
        }

        // Gets the Content-Encoding HTTP response header.
        internal String GetHttpHeaderContentEncoding() {
            string coding = null;
            if (_wr is IIS7WorkerRequest) {
                if (_headers != null) {
                    coding = _headers["Content-Encoding"];
                }
            }
            else if (_customHeaders != null) {
                int numCustomHeaders = _customHeaders.Count;
                for (int i = 0; i < numCustomHeaders; i++) {
                    HttpResponseHeader h = (HttpResponseHeader)_customHeaders[i];
                    if (h.Name == "Content-Encoding") {
                        coding = h.Value;
                        break;
                    }
                }
            }
            return coding;
        }

        /*
         * Content-type
         */

        /// <devdoc>
        ///    <para>Gets or sets the
        ///       HTTP MIME type of output.</para>
        /// </devdoc>
        public String ContentType {
            get {
                return _contentType;
            }

            set {
                if (_headersWritten) {
                    // Don't throw if the new content type is the same as the current one
                    if (_contentType == value)
                        return;

                    throw new HttpException(SR.GetString(SR.Cannot_set_content_type_after_headers_sent));
                }

                _contentTypeSetByManagedCaller = true;
                _contentType = value;
            }
        }


        //    Gets or sets the HTTP charset of output.
        public String Charset {
            get {
                if (_charSet == null)
                    _charSet = ContentEncoding.WebName;

                return _charSet;
            }

            set {
                if (_headersWritten)
                    throw new HttpException(SR.GetString(SR.Cannot_set_content_type_after_headers_sent));

                if (value != null)
                    _charSet = value;
                else
                    _charSet = String.Empty;  // to differentiate between not set (default) and empty chatset

                _customCharSet = true;
            }
        }

        // Content encoding for conversion
        //   Gets or sets the HTTP character set of output.
        public Encoding ContentEncoding {
            get {
                if (_encoding == null) {
                    // use LKG config because Response.ContentEncoding is need to display [config] error
                    GlobalizationSection globConfig = RuntimeConfig.GetLKGConfig(_context).Globalization;
                    if (globConfig != null)
                        _encoding = globConfig.ResponseEncoding;

                    if (_encoding == null)
                        _encoding = Encoding.Default;
                }

                return _encoding;
            }

            set {
                if (value == null)
                    throw new ArgumentNullException("value");

                if (_encoding == null || !_encoding.Equals(value)) {
                    _encoding = value;
                    _encoder = null;   // flush cached encoder

                    if (_httpWriter != null)
                        _httpWriter.UpdateResponseEncoding();
                }
            }
        }


        public Encoding HeaderEncoding {
            get {
                if (_headerEncoding == null) {
                    // use LKG config because Response.ContentEncoding is need to display [config] error
                    GlobalizationSection globConfig = RuntimeConfig.GetLKGConfig(_context).Globalization;
                    if (globConfig != null)
                        _headerEncoding = globConfig.ResponseHeaderEncoding;

                    // default to UTF-8 (also for Unicode as headers cannot be double byte encoded)
                    if (_headerEncoding == null || _headerEncoding.Equals(Encoding.Unicode))
                        _headerEncoding = Encoding.UTF8;
                }

                return _headerEncoding;
            }

            set {
                if (value == null)
                    throw new ArgumentNullException("value");

                if (value.Equals(Encoding.Unicode)) {
                    throw new HttpException(SR.GetString(SR.Invalid_header_encoding, value.WebName));
                }

                if (_headerEncoding == null || !_headerEncoding.Equals(value)) {
                    if (_headersWritten)
                        throw new HttpException(SR.GetString(SR.Cannot_set_header_encoding_after_headers_sent));

                    _headerEncoding = value;
                }
            }
        }

        // Encoder cached for the current encoding
        internal Encoder ContentEncoder {
            get {
                if (_encoder == null) {
                    Encoding e = ContentEncoding;
                    _encoder = e.GetEncoder();

                    // enable best fit mapping accoding to config
                    // (doesn't apply to utf-8 which is the default, thus optimization)

                    if (!e.Equals(Encoding.UTF8)) {
                        bool enableBestFit = false;

                        GlobalizationSection globConfig = RuntimeConfig.GetLKGConfig(_context).Globalization;
                        if (globConfig != null) {
                            enableBestFit = globConfig.EnableBestFitResponseEncoding;
                        }

                        if (!enableBestFit) {
                            // setting 'fallback' disables best fit mapping
                            _encoder.Fallback = new EncoderReplacementFallback();
                        }
                    }
                }
                return _encoder;
            }
        }

        // Cache policy
        //    Returns the caching semantics of the Web page (expiration time, privacy, vary clauses).
        public HttpCachePolicy Cache {
            get {
                if (_cachePolicy == null) {
                    _cachePolicy = new HttpCachePolicy();
                }

                return _cachePolicy;
            }
        }

        // Return whether or not we have cache policy. We don't want to create it in
        // situations where we don't modify it.
        internal bool HasCachePolicy {
            get {
                return _cachePolicy != null;
            }
        }

        // Client connected flag
        //   Gets a value indicating whether the client is still connected to the server.
        public bool IsClientConnected {
            get {
                if (_clientDisconnected)
                    return false;

                if (_wr != null && !_wr.IsClientConnected()) {
                    _clientDisconnected = true;
                    return false;
                }

                return true;
            }
        }

        /// <summary>
        /// Returns a CancellationToken that is tripped when the client disconnects. This can be used
        /// to listen for async disconnect notifications.
        /// </summary>
        /// <remarks>
        /// This method requires that the application be hosted on IIS 7.5 or higher and that the
        /// application pool be running the integrated mode pipeline.
        /// 
        /// Consumers should be aware of some restrictions when consuming this CancellationToken.
        /// Failure to heed these warnings can lead to race conditions, deadlocks, or other
        /// undefined behavior.
        /// 
        /// - This API is thread-safe. However, ASP.NET will dispose of the token object at the
        ///   end of the request. Consumers should exercise caution and ensure that they're not
        ///   calling into this API outside the bounds of a single request. This is similar to
        ///   the contract with BCL Task-returning methods which take a CancellationToken as a
        ///   parameter: the callee should not touch the CancellationToken after the returned
        ///   Task transitions to a terminal state.
        /// 
        /// - DO NOT wait on the CancellationToken.WaitHandle, as this defeats the purpose of an
        ///   async notification and can cause deadlocks.
        /// 
        /// - DO NOT call the CancellationToken.Register overloads which invoke the callback on
        ///   the original SynchronizationContext.
        /// 
        /// - DO NOT consume HttpContext or other non-thread-safe ASP.NET intrinsic objects from
        ///   within the callback provided to Register. Remember: the callback may be running
        ///   concurrently with other ASP.NET or application code.
        /// 
        /// - DO keep the callback methods short-running and non-blocking. Make every effort to
        ///   avoid throwing exceptions from within the callback methods.
        /// 
        /// - We do not guarantee that we will ever transition the token to a canceled state.
        ///   For example, if the request finishes without the client having disconnected, we
        ///   will dispose of this token as mentioned earlier without having first canceled it.
        /// </remarks>
        public CancellationToken ClientDisconnectedToken {
            get {
                IIS7WorkerRequest wr = _wr as IIS7WorkerRequest;
                CancellationToken cancellationToken;
                if (wr != null && wr.TryGetClientDisconnectedCancellationToken(out cancellationToken)) {
                    return cancellationToken;
                }
                else {
                    throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_75_Integrated));
                }
            }
        }

        public bool IsRequestBeingRedirected {
            get {
                return _isRequestBeingRedirected;
            }
            internal set {
                _isRequestBeingRedirected = value;
            }
        }


        /// <devdoc>
        ///    <para>Gets or Sets a redirection string (value of location resposne header) for redirect response.</para>
        /// </devdoc>
        public String RedirectLocation {
            get { return _redirectLocation; }
            set {
                if (_headersWritten)
                    throw new HttpException(SR.GetString(SR.Cannot_append_header_after_headers_sent));

                _redirectLocation = value;
                _redirectLocationSet = true;
            }
        }

        /*
         * Disconnect client
         */

        /// <devdoc>
        ///    <para>Closes the socket connection to a client.</para>
        /// </devdoc>
        public void Close() {
            if (!_clientDisconnected && !_completed && _wr != null) {
                _wr.CloseConnection();
                _clientDisconnected = true;
            }
        }

        // TextWriter object
        //    Enables custom output to the outgoing Http content body.
        public TextWriter Output {
            get { return _writer;}
            set { _writer = value; }
        }

        internal TextWriter SwitchWriter(TextWriter writer) {
            TextWriter oldWriter = _writer;
            _writer = writer;
            return oldWriter;
        }

        // Output stream
        //       Enables binary output to the outgoing Http content body.
        public Stream OutputStream {
            get {
                if (!UsingHttpWriter)
                    throw new HttpException(SR.GetString(SR.OutputStream_NotAvail));

                return _httpWriter.OutputStream;
            }
        }

        // ASP classic compat
        //    Writes a string of binary characters to the HTTP output stream.
        public void BinaryWrite(byte[] buffer) {
            OutputStream.Write(buffer, 0, buffer.Length);
        }


        //  Appends a PICS (Platform for Internet Content Selection) label HTTP header to the output stream.
        public void Pics(String value) {
            AppendHeader("PICS-Label", value);
        }

        // Filtering stream
        //       Specifies a wrapping filter object to modify HTTP entity body before transmission.
        public Stream Filter {
            get {
                if (UsingHttpWriter)
                    return _httpWriter.GetCurrentFilter();
                else
                    return null;
            }

            set {
                if (UsingHttpWriter) {
                    _httpWriter.InstallFilter(value);

                    IIS7WorkerRequest iis7WorkerRequest = _wr as IIS7WorkerRequest;
                    if (iis7WorkerRequest != null) {
                        iis7WorkerRequest.ResponseFilterInstalled();
                    }
                }
                else
                    throw new HttpException(SR.GetString(SR.Filtering_not_allowed));
            }

        }

        // Flag to suppress writing of content
        //    Gets or sets a value indicating that HTTP content will not be sent to client.
        public bool SuppressContent {
            get {
                return _suppressContent;
            }

            set {
                _suppressContent = value;
                _suppressContentSet = true;
            }
        }

        //
        // Public methods
        //

        /*
          * Add Http custom header
          *
          * @param name header name
          * @param value header value
          */

        /// <devdoc>
        ///    <para>Adds an HTTP
        ///       header to the output stream.</para>
        /// </devdoc>
        public void AppendHeader(String name, String value) {
            bool isCacheHeader = false;

            if (_headersWritten)
                throw new HttpException(SR.GetString(SR.Cannot_append_header_after_headers_sent));

            // some headers are stored separately or require special action
            int knownHeaderIndex = HttpWorkerRequest.GetKnownResponseHeaderIndex(name);

            switch (knownHeaderIndex) {
                case HttpWorkerRequest.HeaderContentType:
                    ContentType = value;
                    return; // don't keep as custom header

                case HttpWorkerRequest.HeaderContentLength:
                    _contentLengthSet = true;
                    break;

                case HttpWorkerRequest.HeaderLocation:
                    RedirectLocation = value;
                    return; // don't keep as custom header

                case HttpWorkerRequest.HeaderTransferEncoding:
                    _transferEncodingSet = true;
                    break;

                case HttpWorkerRequest.HeaderCacheControl:
                    _cacheControlHeaderAdded = true;
                    goto case HttpWorkerRequest.HeaderExpires;
                case HttpWorkerRequest.HeaderExpires:
                case HttpWorkerRequest.HeaderLastModified:
                case HttpWorkerRequest.HeaderEtag:
                case HttpWorkerRequest.HeaderVary:
                    isCacheHeader = true;
                    break;
            }

            // In integrated mode, write the headers directly
            if (_wr is IIS7WorkerRequest) {
                Headers.Add(name, value);
            }
            else {
                if (isCacheHeader)
                {
                    // don't keep as custom header
                    if (_cacheHeaders == null) {
                        _cacheHeaders = new ArrayList();
                    }

                    _cacheHeaders.Add(new HttpResponseHeader(knownHeaderIndex, value));
                    return;
                }
                else {
                    HttpResponseHeader h;
                    if (knownHeaderIndex >= 0)
                        h = new HttpResponseHeader(knownHeaderIndex, value);
                    else
                        h = new HttpResponseHeader(name, value);

                    AppendHeader(h);
                }
            }
        }


        /// <internalonly/>
        /// <devdoc>
        ///    <para>
        ///       Adds an HTTP
        ///       cookie to the output stream.
        ///    </para>
        /// </devdoc>
        public void AppendCookie(HttpCookie cookie) {
            if (_headersWritten)
                throw new HttpException(SR.GetString(SR.Cannot_append_cookie_after_headers_sent));

            Cookies.AddCookie(cookie, true);
            OnCookieAdd(cookie);
        }


        /// <internalonly/>
        /// <devdoc>
        /// </devdoc>
        public void SetCookie(HttpCookie cookie) {
            if (_headersWritten)
                throw new HttpException(SR.GetString(SR.Cannot_append_cookie_after_headers_sent));

            Cookies.AddCookie(cookie, false);
            OnCookieCollectionChange();
        }

        internal void BeforeCookieCollectionChange() {
            if (_headersWritten)
                throw new HttpException(SR.GetString(SR.Cannot_modify_cookies_after_headers_sent));
        }

        internal void OnCookieAdd(HttpCookie cookie) {
            // add to request's cookies as well
            Request.AddResponseCookie(cookie);
        }

        internal void OnCookieCollectionChange() {
            // synchronize with request cookie collection
            Request.ResetCookies();
        }

        // Clear response headers
        //    Clears all headers from the buffer stream.
        public void ClearHeaders() {
            if (_headersWritten)
                throw new HttpException(SR.GetString(SR.Cannot_clear_headers_after_headers_sent));

            StatusCode = 200;
            _subStatusCode = 0;
            _statusDescription = null;

            _contentType = "text/html";
            _contentTypeSetByManagedCaller = false;
            _charSet = null;
            _customCharSet = false;
            _contentLengthSet = false;

            _redirectLocation = null;
            _redirectLocationSet = false;
            _isRequestBeingRedirected = false;

            _customHeaders = null;

            if (_headers != null) {
                _headers.ClearInternal();
            }

            _transferEncodingSet = false;
            _chunked = false;

            if (_cookies != null) {
                _cookies.Reset();
                Request.ResetCookies();
            }

            if (_cachePolicy != null) {
                _cachePolicy.Reset();
            }

            _cacheControlHeaderAdded = false;
            _cacheHeaders = null;

            _suppressHeaders = false;
            _suppressContent = false;
            _suppressContentSet = false;

            _expiresInMinutes = 0;
            _expiresInMinutesSet = false;
            _expiresAbsolute = DateTime.MinValue;
            _expiresAbsoluteSet = false;
            _cacheControl = null;

            IIS7WorkerRequest iis7WorkerRequest = _wr as IIS7WorkerRequest;
            if (iis7WorkerRequest != null) {
                // clear the native response as well
                ClearNativeResponse(false, true, iis7WorkerRequest);
                // DevDiv 162749:
                // We need to regenerate Cache-Control: private only when the handler is managed and
                // configuration has <outputCache sendCacheControlHeader="true" /> in system.web
                // caching section.
                if (_handlerHeadersGenerated && _sendCacheControlHeader) {
                    Headers.Set("Cache-Control", "private");
                }
                _handlerHeadersGenerated = false;
            }
        }


        /// <devdoc>
        ///    <para>Clears all content output from the buffer stream.</para>
        /// </devdoc>
        public void ClearContent() {
            Clear();
        }

        /*
         * Clear response buffer and headers. (For ASP compat doesn't clear headers)
         */

        /// <devdoc>
        ///    <para>Clears all headers and content output from the buffer stream.</para>
        /// </devdoc>
        public void Clear() {
            if (UsingHttpWriter)
                _httpWriter.ClearBuffers();

            IIS7WorkerRequest iis7WorkerRequest = _wr as IIS7WorkerRequest;
            if (iis7WorkerRequest != null) {
                // clear the native response buffers too
                ClearNativeResponse(true, false, iis7WorkerRequest);
            }


        }

        /*
         * Clear response buffer and headers. Internal. Used to be 'Clear'.
         */
        internal void ClearAll() {
            if (!_headersWritten)
                ClearHeaders();
            Clear();
        }

        /*
         * Flush response currently buffered
         */

        /// <devdoc>
        ///    <para>Sends all currently buffered output to the client.</para>
        /// </devdoc>
        public void Flush() {
            if (_completed)
                throw new HttpException(SR.GetString(SR.Cannot_flush_completed_response));

            Flush(false);
        }

        // Registers a callback that the ASP.NET runtime will invoke immediately before
        // response headers are sent for this request. This differs from the IHttpModule-
        // level pipeline event in that this is a per-request subscription rather than
        // a per-application subscription. The intent is that the callback may modify
        // the response status code or may set a response cookie or header. Other usage
        // notes and caveats:
        //
        // - This API is available only in the IIS integrated mode pipeline and only
        //   if response headers haven't yet been sent for this request.
        // - The ASP.NET runtime does not guarantee anything about the thread that the
        //   callback is invoked on. For example, the callback may be invoked synchronously
        //   on a background thread if a background flush is being performed.
        //   HttpContext.Current is not guaranteed to be available on such a thread.
        // - The callback must not call any API that manipulates the response entity body
        //   or that results in a flush. For example, the callback must not call
        //   Response.Redirect, as that method may manipulate the response entity body.
        // - The callback must contain only short-running synchronous code. Trying to kick
        //   off an asynchronous operation or wait on such an operation could result in
        //   a deadlock.
        // - The callback must not throw, otherwise behavior is undefined.
        [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate", Justification = @"The normal event pattern doesn't work between HttpResponse and HttpResponseBase since the signatures differ.")]
        public ISubscriptionToken AddOnSendingHeaders(Action<HttpContext> callback) {
            if (callback == null) {
                throw new ArgumentNullException("callback");
            }

            if (!(_wr is IIS7WorkerRequest)) {
                throw new PlatformNotSupportedException(SR.GetString(SR.Requires_Iis_Integrated_Mode));
            }

            if (HeadersWritten) {
                throw new HttpException(SR.GetString(SR.Cannot_call_method_after_headers_sent_generic));
            }

            return _onSendingHeadersSubscriptionQueue.Enqueue(callback);
        }

        /*
         * Append string to the log record
         *
         * @param param string to append to the log record
         */

        /// <devdoc>
        ///    <para>Adds custom log information to the IIS log file.</para>
        /// </devdoc>
        [AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Medium)]
        public void AppendToLog(String param) {
            // only makes sense for IIS
            if (_wr is System.Web.Hosting.ISAPIWorkerRequest)
                ((System.Web.Hosting.ISAPIWorkerRequest)_wr).AppendLogParameter(param);
            else if (_wr is System.Web.Hosting.IIS7WorkerRequest)
                _context.Request.AppendToLogQueryString(param);
        }


        /// <devdoc>
        ///    <para>Redirects a client to a new URL.</para>
        /// </devdoc>
        public void Redirect(String url) {
            Redirect(url, true, false);
        }

        /// <devdoc>
        ///    <para>Redirects a client to a new URL.</para>
        /// </devdoc>
        public void Redirect(String url, bool endResponse) {
            Redirect(url, endResponse, false);
        }

        public void RedirectToRoute(object routeValues) {
            RedirectToRoute(new RouteValueDictionary(routeValues));
        }

        public void RedirectToRoute(string routeName) {
            RedirectToRoute(routeName, (RouteValueDictionary)null, false);
        }

        public void RedirectToRoute(RouteValueDictionary routeValues) {
            RedirectToRoute(null /* routeName */, routeValues, false);
        }

        public void RedirectToRoute(string routeName, object routeValues) {
            RedirectToRoute(routeName, new RouteValueDictionary(routeValues), false);
        }

        public void RedirectToRoute(string routeName, RouteValueDictionary routeValues) {
            RedirectToRoute(routeName, routeValues, false);
        }

        private void RedirectToRoute(string routeName, RouteValueDictionary routeValues, bool permanent) {
            string destinationUrl = null;
            VirtualPathData data = RouteTable.Routes.GetVirtualPath(Request.RequestContext, routeName, routeValues);
            if (data != null) {
                destinationUrl = data.VirtualPath;
            }

            if (String.IsNullOrEmpty(destinationUrl)) {
                throw new InvalidOperationException(SR.GetString(SR.No_Route_Found_For_Redirect));
            }

            Redirect(destinationUrl, false /* endResponse */, permanent);
        }

        public void RedirectToRoutePermanent(object routeValues) {
            RedirectToRoutePermanent(new RouteValueDictionary(routeValues));
        }

        public void RedirectToRoutePermanent(string routeName) {
            RedirectToRoute(routeName, (RouteValueDictionary)null, true);
        }

        public void RedirectToRoutePermanent(RouteValueDictionary routeValues) {
            RedirectToRoute(null /* routeName */, routeValues, true);
        }

        public void RedirectToRoutePermanent(string routeName, object routeValues) {
            RedirectToRoute(routeName, new RouteValueDictionary(routeValues), true);
        }

        public void RedirectToRoutePermanent(string routeName, RouteValueDictionary routeValues) {
            RedirectToRoute(routeName, routeValues, true);
        }


        /// <devdoc>
        ///    <para>Redirects a client to a new URL with a 301.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification="Warning was suppressed for consistency with existing similar Redirect API")]
        public void RedirectPermanent(String url) {
            Redirect(url, true, true);
        }

        /// <devdoc>
        ///    <para>Redirects a client to a new URL with a 301.</para>
        /// </devdoc>
        [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings",
            Justification = "Warning was suppressed for consistency with existing similar Redirect API")]
        public void RedirectPermanent(String url, bool endResponse) {
            Redirect(url, endResponse, true);
        }

        internal void Redirect(String url, bool endResponse, bool permanent) {
#if DBG
            string originalUrl = url;
#endif
            if (url == null)
                throw new ArgumentNullException("url");

            if (url.IndexOf('\n') >= 0)
                throw new ArgumentException(SR.GetString(SR.Cannot_redirect_to_newline));

            if (_headersWritten)
                throw new HttpException(SR.GetString(SR.Cannot_redirect_after_headers_sent));

            Page page = _context.Handler as Page;
            if ((page != null) && page.IsCallback) {
                throw new ApplicationException(SR.GetString(SR.Redirect_not_allowed_in_callback));
            }

            url = ApplyRedirectQueryStringIfRequired(url);

            url = ApplyAppPathModifier(url);

            url = ConvertToFullyQualifiedRedirectUrlIfRequired(url);

            url = UrlEncodeRedirect(url);

            Clear();

            // If it's a Page and SmartNavigation is on, return a short script
            // to perform the redirect instead of returning a 302 (bugs ASURT 82331/86782)
#pragma warning disable 0618    // To avoid SmartNavigation deprecation warning
            if (page != null && page.IsPostBack && page.SmartNavigation && (Request["__smartNavPostBack"] == "true")) {
#pragma warning restore 0618
                Write("<BODY><ASP_SMARTNAV_RDIR url=\"");
                Write(HttpUtility.HtmlEncode(url));
                Write("\"></ASP_SMARTNAV_RDIR>");

                Write("</BODY>");
            }
            else {
                this.StatusCode = permanent ? 301 : 302;
                RedirectLocation = url;
                // DevDivBugs 158137: 302 Redirect vulnerable to XSS
                // A ---- of protocol identifiers. We don't want to UrlEncode
                // URLs matching these schemes in order to not break the
                // physical Object Moved to link.
                if (UriUtil.IsSafeScheme(url)) {
                    url = HttpUtility.HtmlAttributeEncode(url);
                }
                else {
                    url = HttpUtility.HtmlAttributeEncode(HttpUtility.UrlEncode(url));
                }
                Write("<html><head><title>Object moved</title></head><body>\r\n");
                Write("<h2>Object moved to <a href=\"" + url + "\">here</a>.</h2>\r\n");
                Write("</body></html>\r\n");
            }

            _isRequestBeingRedirected = true;

#if DBG
            Debug.Trace("ClientUrl", "*** Redirect (" + originalUrl + ") --> " + RedirectLocation + " ***");
#endif

            var redirectingHandler = Redirecting;
            if (redirectingHandler != null) {
                redirectingHandler(this, EventArgs.Empty);
            }

            if (endResponse)
                End();
        }

        internal string ApplyRedirectQueryStringIfRequired(string url) {
            if (Request == null || (string)Request.Browser["requiresPostRedirectionHandling"] != "true")
                return url;

            Page page = _context.Handler as Page;
            if (page != null && !page.IsPostBack)
                return url;

            //do not add __redir=1 if it already exists
            int i = url.IndexOf(RedirectQueryStringAssignment, StringComparison.Ordinal);
            if(i == -1) {
                i = url.IndexOf('?');
                if (i >= 0) {
                    url = url.Insert(i + 1, _redirectQueryStringInline);
                }
                else {
                    url = String.Concat(url, _redirectQueryString);
                }
            }
            return url;
        }

        //
        // Redirect to error page appending ?aspxerrorpath if no query string in the url.
        // Fails to redirect if request is already for error page.
        // Suppresses all errors.
        // See comments on RedirectToErrorPageStatus type for meaning of return values.
        //
        internal RedirectToErrorPageStatus RedirectToErrorPage(String url, CustomErrorsRedirectMode redirectMode) {
            const String qsErrorMark = "aspxerrorpath";

            try {
                if (String.IsNullOrEmpty(url))
                    return RedirectToErrorPageStatus.NotAttempted;   // nowhere to redirect

                if (_headersWritten)
                    return RedirectToErrorPageStatus.NotAttempted;

                if (Request.QueryString[qsErrorMark] != null)
                    return RedirectToErrorPageStatus.Failed;   // already in error redirect

                if (redirectMode == CustomErrorsRedirectMode.ResponseRewrite) {
                    Context.Server.Execute(url);
                }
                else {
                    // append query string
                    if (url.IndexOf('?') < 0)
                        url = url + "?" + qsErrorMark + "=" + HttpEncoderUtility.UrlEncodeSpaces(Request.Path);

                    // redirect without response.end
                    Redirect(url, false /*endResponse*/);
                }
            }
            catch {
                return RedirectToErrorPageStatus.Failed;
            }

            return RedirectToErrorPageStatus.Success;
        }

        // Represents the result of calling RedirectToErrorPage
        internal enum RedirectToErrorPageStatus {
            NotAttempted, // Redirect or rewrite was not attempted, possibly because no redirect URL was specified
            Success, // Redirect or rewrite was attempted and succeeded
            Failed // Redirect or rewrite was attempted and failed, possibly due to the error page throwing
        }

        // Implementation of the DefaultHttpHandler for IIS6+
        internal bool CanExecuteUrlForEntireResponse {
            get {
                // if anything is sent, too late
                if (_headersWritten) {
                    return false;
                }

                // must have the right kind of worker request
                if (_wr == null || !_wr.SupportsExecuteUrl) {
                    return false;
                }

                // must not be capturing output to custom writer
                if (!UsingHttpWriter) {
                    return false;
                }

                // there is some cached output not yet sent
                if (_httpWriter.GetBufferedLength() != 0) {
                    return false;
                }

                // can't use execute url with filter installed
                if (_httpWriter.FilterInstalled) {
                    return false;
                }

                if (_cachePolicy != null && _cachePolicy.IsModified()) {
                    return false;
                }

                return true;
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This is a safe critical method.")]
        internal IAsyncResult BeginExecuteUrlForEntireResponse(
                                    String pathOverride, NameValueCollection requestHeaders,
                                    AsyncCallback cb, Object state) {
            Debug.Assert(CanExecuteUrlForEntireResponse);

            // prepare user information
            String userName, userAuthType;
            if (_context != null && _context.User != null) {
                userName     = _context.User.Identity.Name;
                userAuthType = _context.User.Identity.AuthenticationType;
            }
            else {
                userName = String.Empty;
                userAuthType = String.Empty;
            }

            // get the path
            String path = Request.RewrittenUrl; // null is ok

            if (pathOverride != null) {
                path = pathOverride;
            }

            // get the headers
            String headers = null;

            if (requestHeaders != null) {
                int numHeaders = requestHeaders.Count;

                if (numHeaders > 0) {
                    StringBuilder sb = new StringBuilder();

                    for (int i = 0; i < numHeaders; i++) {
                        sb.Append(requestHeaders.GetKey(i));
                        sb.Append(": ");
                        sb.Append(requestHeaders.Get(i));
                        sb.Append("\r\n");
                    }

                    headers = sb.ToString();
                }
            }

            byte[] entity = null;
            if (_context != null && _context.Request != null) {
                entity = _context.Request.EntityBody;
            }

            Debug.Trace("ExecuteUrl", "HttpResponse.BeginExecuteUrlForEntireResponse:" +
                " path=" + path + " headers=" + headers +
                " userName=" + userName + " authType=" + userAuthType);

            // call worker request to start async execute url for this request
            IAsyncResult ar = _wr.BeginExecuteUrl(
                    path,
                    null, // this method
                    headers,
                    true, // let execute url send headers
                    true, // add user info
                    _wr.GetUserToken(),
                    userName,
                    userAuthType,
                    entity,
                    cb,
                    state);

            // suppress further sends from ASP.NET
            // (only if succeeded starting async operation - not is 'finally' block)
            _headersWritten = true;
            _ended = true;

            return ar;
        }

        internal void EndExecuteUrlForEntireResponse(IAsyncResult result) {
            Debug.Trace("ExecuteUrl", "HttpResponse.EndExecuteUrlForEntireResponse");
            _wr.EndExecuteUrl(result);
        }

        // Methods to write from file

        //    Writes values to an HTTP output content stream.
        public void Write(String s) {
            _writer.Write(s);
        }

        // Writes values to an HTTP output content stream.
        public void Write(Object obj) {
            _writer.Write(obj);
        }


        /// <devdoc>
        ///    <para>Writes values to an HTTP output content stream.</para>
        /// </devdoc>
        public void Write(char ch) {
            _writer.Write(ch);
        }


        /// <devdoc>
        ///    <para>Writes values to an HTTP output content stream.</para>
        /// </devdoc>
        public void Write(char[] buffer, int index, int count) {
            _writer.Write(buffer, index, count);
        }


        /// <devdoc>
        ///    <para>Writes a substition block to the response.</para>
        /// </devdoc>
        public void WriteSubstitution(HttpResponseSubstitutionCallback callback) {
            // cannot be instance method on a control
            if (callback.Target != null && callback.Target is Control) {
                throw new ArgumentException(SR.GetString(SR.Invalid_substitution_callback), "callback");
            }

            if (UsingHttpWriter) {
                // HttpWriter can take substitution blocks
                _httpWriter.WriteSubstBlock(callback, _wr as IIS7WorkerRequest);
            }
            else {
                // text writer -- write as string
                _writer.Write(callback(_context));
            }

            // set the cache policy: reduce cachability from public to server
            if (_cachePolicy != null && _cachePolicy.GetCacheability() == HttpCacheability.Public)
                _cachePolicy.SetCacheability(HttpCacheability.Server);
        }

        /*
         * Helper method to write from file stream
         *
         * Handles only TextWriter case. For real requests
         * HttpWorkerRequest can take files
         */
        private void WriteStreamAsText(Stream f, long offset, long size) {
            if (size < 0)
                size = f.Length - offset;

            if (size > 0) {
                if (offset > 0)
                    f.Seek(offset, SeekOrigin.Begin);

                byte[] fileBytes = new byte[(int)size];
                int bytesRead = f.Read(fileBytes, 0, (int)size);
                _writer.Write(Encoding.Default.GetChars(fileBytes, 0, bytesRead));
            }
        }

        // support for VirtualPathProvider
        internal void WriteVirtualFile(VirtualFile vf) {
            Debug.Trace("WriteVirtualFile", vf.Name);

            using (Stream s = vf.Open()) {
                if (UsingHttpWriter) {
                    long size = s.Length;

                    if (size > 0) {
                        // write as memory block
                        byte[] fileBytes = new byte[(int)size];
                        int bytesRead = s.Read(fileBytes, 0, (int) size);
                        _httpWriter.WriteBytes(fileBytes, 0, bytesRead);
                    }
                }
                else {
                    // Write file contents
                    WriteStreamAsText(s, 0, -1);
                }
            }
        }

        // Helper method to get absolute physical filename from the argument to WriteFile
        private String GetNormalizedFilename(String fn) {
            // If it's not a physical path, call MapPath on it
            if (!UrlPath.IsAbsolutePhysicalPath(fn)) {
                if (Request != null)
                    fn = Request.MapPath(fn); // relative to current request
                else
                    fn = HostingEnvironment.MapPath(fn);
            }

            return fn;
        }

        // Write file
        ///  Writes a named file directly to an HTTP content output stream.
        public void WriteFile(String filename) {
            if (filename == null) {
                throw new ArgumentNullException("filename");
            }

            WriteFile(filename, false);
        }

        /*
         * Write file
         *
         * @param filename file to write
         * @readIntoMemory flag to read contents into memory immediately
         */

        /// <devdoc>
        ///    <para> Reads a file into a memory block.</para>
        /// </devdoc>
        public void WriteFile(String filename, bool readIntoMemory) {
            if (filename == null) {
                throw new ArgumentNullException("filename");
            }

            filename = GetNormalizedFilename(filename);

            FileStream f = null;

            try {
                f = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);

                if (UsingHttpWriter) {
                    long size = f.Length;

                    if (size > 0) {
                        if (readIntoMemory) {
                            // write as memory block
                            byte[] fileBytes = new byte[(int)size];
                            int bytesRead = f.Read(fileBytes, 0, (int) size);
                            _httpWriter.WriteBytes(fileBytes, 0, bytesRead);
                        }
                        else {
                            // write as file block
                            f.Close(); // close before writing
                            f = null;
                            _httpWriter.WriteFile(filename, 0, size);
                        }
                    }
                }
                else {
                    // Write file contents
                    WriteStreamAsText(f, 0, -1);
                }
            }
            finally {
                if (f != null)
                    f.Close();
            }
        }


        public void TransmitFile(string filename) {
            TransmitFile(filename, 0, -1);
        }
        public void TransmitFile(string filename, long offset, long length) {
            if (filename == null) {
                throw new ArgumentNullException("filename");
            }
            if (offset < 0)
                throw new ArgumentException(SR.GetString(SR.Invalid_range), "offset");
            if (length < -1)
                throw new ArgumentException(SR.GetString(SR.Invalid_range), "length");

            filename = GetNormalizedFilename(filename);

            long size;
            using (FileStream f = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                size = f.Length;
                // length of -1 means send rest of file
                if (length == -1) {
                    length =  size - offset;
                }
                if (size < offset) {
                    throw new ArgumentException(SR.GetString(SR.Invalid_range), "offset");
                }
                else if ((size - offset) < length) {
                    throw new ArgumentException(SR.GetString(SR.Invalid_range), "length");
                }
                if (!UsingHttpWriter) {
                    WriteStreamAsText(f, offset, length);
                    return;
                }
            }

            if (length > 0) {
                bool supportsLongTransmitFile = (_wr != null && _wr.SupportsLongTransmitFile);

                _httpWriter.TransmitFile(filename, offset, length,
                   _context.IsClientImpersonationConfigured || HttpRuntime.IsOnUNCShareInternal, supportsLongTransmitFile);
            }
        }


        private void ValidateFileRange(String filename, long offset, long length) {
            FileStream f = null;

            try {
                f = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);

                long fileSize = f.Length;

                if (length == -1)
                    length = fileSize - offset;

                if (offset < 0 || length > fileSize - offset)
                    throw new HttpException(SR.GetString(SR.Invalid_range));
            }
            finally {
                if (f != null)
                    f.Close();
            }
        }

        /*
         * Write file
         *
         * @param filename file to write
         * @param offset file offset to start writing
         * @param size number of bytes to write
         */

        /// <devdoc>
        ///    <para>Writes a file directly to an HTTP content output stream.</para>
        /// </devdoc>
        public void WriteFile(String filename, long offset, long size) {
            if (filename == null) {
                throw new ArgumentNullException("filename");
            }

            if (size == 0)
                return;

            filename = GetNormalizedFilename(filename);

            ValidateFileRange(filename, offset, size);

            if (UsingHttpWriter) {
                // HttpWriter can take files -- don't open here (but Demand permission)
                InternalSecurityPermissions.FileReadAccess(filename).Demand();
                _httpWriter.WriteFile(filename, offset, size);
            }
            else {
                FileStream f = null;

                try {
                    f = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
                    WriteStreamAsText(f, offset, size);
                }
                finally {
                    if (f != null)
                        f.Close();
                }
            }
        }

        /*
         * Write file
         *
         * @param handle file to write
         * @param offset file offset to start writing
         * @param size number of bytes to write
         */

        /// <devdoc>
        ///    <para>Writes a file directly to an HTTP content output stream.</para>
        /// </devdoc>
        [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
        public void WriteFile(IntPtr fileHandle, long offset, long size) {
            if (size <= 0)
                return;

            FileStream f = null;

            try {
                f = new FileStream(new Microsoft.Win32.SafeHandles.SafeFileHandle(fileHandle,false), FileAccess.Read);

                if (UsingHttpWriter) {
                    long fileSize = f.Length;

                    if (size == -1)
                        size = fileSize - offset;

                    if (offset < 0 || size > fileSize - offset)
                        throw new HttpException(SR.GetString(SR.Invalid_range));

                    if (offset > 0)
                        f.Seek(offset, SeekOrigin.Begin);

                    // write as memory block
                    byte[] fileBytes = new byte[(int)size];
                    int bytesRead = f.Read(fileBytes, 0, (int)size);
                    _httpWriter.WriteBytes(fileBytes, 0, bytesRead);
                }
                else {
                    WriteStreamAsText(f, offset, size);
                }
            }
            finally {
                if (f != null)
                    f.Close();
            }
        }

        /// <devdoc>
        ///    <para>Allows HTTP/2 Server Push</para>
        /// </devdoc>
        public void PushPromise(string path) {
            // 


            PushPromise(path, method: "GET", headers: null);
        }

        /// <devdoc>
        ///    <para>Allows HTTP/2 Server Push</para>
        /// </devdoc>
        public void PushPromise(string path, string method, NameValueCollection headers) {
            // PushPromise is non-deterministic and application shouldn't have logic that depends on it. 
            // It's only purpose is performance advantage in some cases.
            // There are many conditions (protocol and implementation) that may cause to 
            // ignore the push requests completely.
            // The expectation is based on fire-and-forget 

            if (path == null) {
                throw new ArgumentNullException("path");
            }

            if (method == null) {
                throw new ArgumentNullException("method");
            }

            // Extract an optional query string
            string queryString = string.Empty;
            int i = path.IndexOf('?');

            if (i >= 0) {
                if (i < path.Length - 1) {
                    queryString = path.Substring(i + 1);
                }

                // Remove the query string portion from the path
                path = path.Substring(0, i);
            }


            // Only virtual path is allowed:
            // "/path"   - origin relative
            // "~/path"  - app relative
            // "path"    - request relative
            // "../path" - reduced 
            if (string.IsNullOrEmpty(path) || !UrlPath.IsValidVirtualPathWithoutProtocol(path)) {
                throw new ArgumentException(SR.GetString(SR.Invalid_path_for_push_promise, path));
            }

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

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

                // Do push promise
                IIS7WorkerRequest wr = (IIS7WorkerRequest) _wr;
                wr.PushPromise(virtualPath.VirtualPathString, queryString, method, headers);
            }
            catch (PlatformNotSupportedException e) {
                // Ignore errors if push promise is not supported
                if (Context.TraceIsEnabled) {
                    Context.Trace.Write("aspx", "Push promise is not supported", e);
                }
            }
        }

        //
        // Deprecated ASP compatibility methods and properties
        //


        /// <devdoc>
        ///    <para>
        ///       Same as StatusDescription. Provided only for ASP compatibility.
        ///    </para>
        /// </devdoc>
        public string Status {
            get {
                return this.StatusCode.ToString(NumberFormatInfo.InvariantInfo) + " " + this.StatusDescription;
            }

            set {
                int code = 200;
                String descr = "OK";

                try {
                    int i = value.IndexOf(' ');
                    code = Int32.Parse(value.Substring(0, i), CultureInfo.InvariantCulture);
                    descr = value.Substring(i+1);
                }
                catch {
                    throw new HttpException(SR.GetString(SR.Invalid_status_string));
                }

                this.StatusCode = code;
                this.StatusDescription = descr;
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Same as BufferOutput. Provided only for ASP compatibility.
        ///    </para>
        /// </devdoc>
        public bool Buffer {
            get { return this.BufferOutput;}
            set { this.BufferOutput = value;}
        }


        /// <devdoc>
        ///    <para>Same as Appendheader. Provided only for ASP compatibility.</para>
        /// </devdoc>
        public void AddHeader(String name, String value) {
            AppendHeader(name, value);
        }

        /*
         * Cancelles handler processing of the current request
         * throws special [non-]exception uncatchable by the user code
         * to tell application to stop module execution.
         */

        /// <devdoc>
        ///    <para>Sends all currently buffered output to the client then closes the
        ///       socket connection.</para>
        /// </devdoc>
        public void End() {
            if (_context.IsInCancellablePeriod) {
                AbortCurrentThread();
            }
            else {
                // when cannot abort execution, flush and supress further output
                _endRequiresObservation = true;

                if (!_flushing) { // ignore Reponse.End while flushing (in OnPreSendHeaders)
                    Flush();
                    _ended = true;

                    if (_context.ApplicationInstance != null) {
                        _context.ApplicationInstance.CompleteRequest();
                    }
                }
            }
        }

        // Aborts the current thread if Response.End was called and not yet observed.
        internal void ObserveResponseEndCalled() {
            if (_endRequiresObservation) {
                _endRequiresObservation = false;
                AbortCurrentThread();
            }
        }

        [SuppressMessage("Microsoft.Security", "CA2106:SecureAsserts", Justification = "Known issue, but required for proper operation of ASP.NET.")]
        [SecurityPermission(SecurityAction.Assert, ControlThread = true)]
        private static void AbortCurrentThread() {
            Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false));
        }

        /*
         * ASP compatible caching properties
         */


        /// <devdoc>
        ///    <para>
        ///       Gets or sets the time, in minutes, until cached
        ///       information will be removed from the cache. Provided for ASP compatiblility. Use
        ///       the <see cref='System.Web.HttpResponse.Cache'/>
        ///       Property instead.
        ///    </para>
        /// </devdoc>
        public int Expires {
            get {
                return _expiresInMinutes;
            }
            set {
                if (!_expiresInMinutesSet || value < _expiresInMinutes) {
                    _expiresInMinutes = value;
                    Cache.SetExpires(_context.Timestamp + new TimeSpan(0, _expiresInMinutes, 0));
                }
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Gets or sets the absolute time that cached information
        ///       will be removed from the cache. Provided for ASP compatiblility. Use the <see cref='System.Web.HttpResponse.Cache'/>
        ///       property instead.
        ///    </para>
        /// </devdoc>
        public DateTime ExpiresAbsolute {
            get {
                return _expiresAbsolute;
            }
            set {
                if (!_expiresAbsoluteSet || value < _expiresAbsolute) {
                    _expiresAbsolute = value;
                    Cache.SetExpires(_expiresAbsolute);
                }
            }
        }


        /// <devdoc>
        ///    <para>
        ///       Provided for ASP compatiblility. Use the <see cref='System.Web.HttpResponse.Cache'/>
        ///       property instead.
        ///    </para>
        /// </devdoc>
        public string CacheControl {
            get {
                if (_cacheControl == null) {
                    // the default
                    return "private";
                }

                return _cacheControl;
            }
            set {
                if (String.IsNullOrEmpty(value)) {
                    _cacheControl = null;
                    Cache.SetCacheability(HttpCacheability.NoCache);
                }
                else if (StringUtil.EqualsIgnoreCase(value, "private")) {
                    _cacheControl = value;
                    Cache.SetCacheability(HttpCacheability.Private);
                }
                else if (StringUtil.EqualsIgnoreCase(value, "public")) {
                    _cacheControl = value;
                    Cache.SetCacheability(HttpCacheability.Public);
                }
                else if (StringUtil.EqualsIgnoreCase(value, "no-cache")) {
                    _cacheControl = value;
                    Cache.SetCacheability(HttpCacheability.NoCache);
                }
                else {
                    throw new ArgumentException(SR.GetString(SR.Invalid_value_for_CacheControl, value));
                }
            }
        }

        internal void SetAppPathModifier(string appPathModifier) {
            if (appPathModifier != null && (
                appPathModifier.Length == 0 ||
                appPathModifier[0] == '/' ||
                appPathModifier[appPathModifier.Length - 1] == '/')) {

                throw new ArgumentException(SR.GetString(SR.InvalidArgumentValue, "appPathModifier"));
            }

            _appPathModifier = appPathModifier;

            Debug.Trace("ClientUrl", "*** SetAppPathModifier (" + appPathModifier + ") ***");
        }


        public string ApplyAppPathModifier(string virtualPath) {
#if DBG
            string originalUrl = virtualPath;
#endif
            object ch = _context.CookielessHelper; // This ensures that the cookieless-helper is initialized and applies the AppPathModifier
            if (virtualPath == null)
                return null;

            if (UrlPath.IsRelativeUrl(virtualPath)) {
                // DevDiv 173208: RewritePath returns an HTTP 500 error code when requested with certain user agents
                // We should use ClientBaseDir instead of FilePathObject.
                virtualPath = UrlPath.Combine(Request.ClientBaseDir.VirtualPathString, virtualPath);
            }
            else {
                // ignore paths with http://server/... or //
                if (!UrlPath.IsRooted(virtualPath) || virtualPath.StartsWith("//", StringComparison.Ordinal)) {
                    return virtualPath;
                }

                virtualPath = UrlPath.Reduce(virtualPath);
            }

            if (_appPathModifier == null || virtualPath.IndexOf(_appPathModifier, StringComparison.Ordinal) >= 0) {
#if DBG
                Debug.Trace("ClientUrl", "*** ApplyAppPathModifier (" + originalUrl + ") --> " + virtualPath + " ***");
#endif
                return virtualPath;
            }
            
            string appPath = HttpRuntime.AppDomainAppVirtualPathString;

            int compareLength = appPath.Length;
            bool isVirtualPathShort = (virtualPath.Length == appPath.Length - 1);
            if (isVirtualPathShort) {
                compareLength--;
            }

            // String.Compare will throw exception if there aren't compareLength characters
            if (virtualPath.Length < compareLength) {
                return virtualPath;
            }

            if (!StringUtil.EqualsIgnoreCase(virtualPath, 0, appPath, 0, compareLength)) {
                return virtualPath;
            }

            if (isVirtualPathShort) {
                virtualPath += "/";
            }

            Debug.Assert(virtualPath.Length >= appPath.Length);
            if (virtualPath.Length == appPath.Length) {
                virtualPath = virtualPath.Substring(0, appPath.Length) + _appPathModifier + "/";
            }
            else {
                virtualPath =
                    virtualPath.Substring(0, appPath.Length) +
                    _appPathModifier +
                    "/" +
                    virtualPath.Substring(appPath.Length);
            }
#if DBG
            Debug.Trace("ClientUrl", "*** ApplyAppPathModifier (" + originalUrl + ") --> " + virtualPath + " ***");
#endif

            return virtualPath;
        }

        internal String RemoveAppPathModifier(string virtualPath) {
            if (String.IsNullOrEmpty(_appPathModifier))
                return virtualPath;

            int pos = virtualPath.IndexOf(_appPathModifier, StringComparison.Ordinal);

            if (pos <= 0 || virtualPath[pos-1] != '/')
                return virtualPath;

            return virtualPath.Substring(0, pos-1) + virtualPath.Substring(pos + _appPathModifier.Length);
        }

        internal bool UsePathModifier {
            get {
                return !String.IsNullOrEmpty(_appPathModifier);
            }
        }

        private String ConvertToFullyQualifiedRedirectUrlIfRequired(String url) {
            HttpRuntimeSection runtimeConfig = RuntimeConfig.GetConfig(_context).HttpRuntime;
            if (    runtimeConfig.UseFullyQualifiedRedirectUrl ||
                    (Request != null && (string)Request.Browser["requiresFullyQualifiedRedirectUrl"] == "true")) {
                return (new Uri(Request.Url, url)).AbsoluteUri ;
            }
            else {
                return url;
            }
        }

        private String UrlEncodeIDNSafe(String url) {
            // Bug 86594: Should not encode the domain part of the url. For example,
            // http://Übersite/Überpage.aspx should only encode the 2nd Ü.
            // To accomplish this we must separate the scheme+host+port portion of the url from the path portion,
            // encode the path portion, then reconstruct the url.
            Debug.Assert(!url.Contains("?"), "Querystring should have been stripped off.");

            string schemeAndAuthority;
            string path;
            string queryAndFragment;
            bool isValidUrl = UriUtil.TrySplitUriForPathEncode(url, out schemeAndAuthority, out path, out queryAndFragment, checkScheme: true);

            if (isValidUrl) {
                // only encode the path portion
                return schemeAndAuthority + HttpEncoderUtility.UrlEncodeSpaces(HttpUtility.UrlEncodeNonAscii(path, Encoding.UTF8)) + queryAndFragment;
            }
            else {
                // encode the entire URL
                return HttpEncoderUtility.UrlEncodeSpaces(HttpUtility.UrlEncodeNonAscii(url, Encoding.UTF8));
            }
        }

        private String UrlEncodeRedirect(String url) {
            // convert all non-ASCII chars before ? to %XX using UTF-8 and
            // after ? using Response.ContentEncoding

            int iqs = url.IndexOf('?');

            if (iqs >= 0) {
                Encoding qsEncoding = (Request != null) ? Request.ContentEncoding : ContentEncoding;
                url = UrlEncodeIDNSafe(url.Substring(0, iqs)) + HttpUtility.UrlEncodeNonAscii(url.Substring(iqs), qsEncoding);
            }
            else {
                url = UrlEncodeIDNSafe(url);
            }

            return url;
        }

        internal void UpdateNativeResponse(bool sendHeaders)
        {
            IIS7WorkerRequest iis7WorkerRequest = _wr as IIS7WorkerRequest;

            if (null == iis7WorkerRequest) {
                return;
            }

            // WOS 1841024 - Don't set _suppressContent to true for HEAD requests.  IIS needs the content
            // in order to correctly set the Content-Length header.
            // WOS 1634512 - need to clear buffers if _ended == true
            // WOS 1850019 - Breaking Change: ASP.NET v2.0: Content-Length is not correct for pages that call HttpResponse.SuppressContent
            if ((_suppressContent && Request != null && Request.HttpVerb != HttpVerb.HEAD) || _ended)
                Clear();

            bool needPush = false;
            // NOTE: This also sets the response encoding on the HttpWriter
            long bufferedLength = _httpWriter.GetBufferedLength();

            //
            // Set headers and status
            //
            if (!_headersWritten)
            {
                //
                // Set status
                //
                // VSWhidbey 270635: We need to reset the status code for mobile devices.
                if (UseAdaptiveError) {

                    // VSWhidbey 288054: We should change the status code for cases
                    // that cannot be handled by mobile devices
                    // 4xx for Client Error and 5xx for Server Error in HTTP spec
                    int statusCode = StatusCode;
                    if (statusCode >= 400 && statusCode < 600) {
                        this.StatusCode = 200;
                    }
                }

                // DevDiv #782830: Provide a hook where the application can change the response status code
                // or response headers.
                if (sendHeaders && !_onSendingHeadersSubscriptionQueue.IsEmpty) {
                    _onSendingHeadersSubscriptionQueue.FireAndComplete(cb => cb(Context));
                }

                if (_statusSet) {
                    _wr.SendStatus(this.StatusCode, this.SubStatusCode, this.StatusDescription);
                    _statusSet = false;
                }

                //
                //  Set headers
                //
                if (!_suppressHeaders && !_clientDisconnected)
                {
                    if (sendHeaders) {
                        EnsureSessionStateIfNecessary();
                    }

                    // If redirect location set, write it through to IIS as a header
                    if (_redirectLocation != null && _redirectLocationSet) {
                        HttpHeaderCollection headers = Headers as HttpHeaderCollection;
                        headers.Set("Location", _redirectLocation);
                        _redirectLocationSet = false;
                    }

                    // Check if there is buffered response
                    bool responseBuffered = bufferedLength > 0 || iis7WorkerRequest.IsResponseBuffered();

                    //
                    // Generate Content-Type
                    //
                    if (_contentType != null                                              // Valid Content-Type
                        && (_contentTypeSetByManagedCaller                                // Explicitly set by managed caller 
                            || (_contentTypeSetByManagedHandler && responseBuffered))) {  // Implicitly set by managed handler and response is non-empty
                        HttpHeaderCollection headers = Headers as HttpHeaderCollection;
                        String contentType = AppendCharSetToContentType(_contentType);
                        headers.Set("Content-Type", contentType);
                    }

                    //
                    // If cookies have been added/changed, set the corresponding headers
                    //
                    GenerateResponseHeadersForCookies();

                    // Not calling WriteHeaders headers in Integrated mode.
                    // Instead, most headers are generated when the handler runs,
                    // or on demand as necessary.
                    // The only exception are the cache policy headers.
                    if (sendHeaders) {

                        SuppressCachingCookiesIfNecessary();

                        if (_cachePolicy != null) {
                            if (_cachePolicy.IsModified()) {
                                ArrayList cacheHeaders = new ArrayList();
                                _cachePolicy.GetHeaders(cacheHeaders, this);
                                HttpHeaderCollection headers = Headers as HttpHeaderCollection;
                                foreach (HttpResponseHeader header in cacheHeaders) {
                                    // set and override the header
                                    headers.Set(header.Name, header.Value);
                                }
                            }
                        }

                        needPush = true;
                    }
                }
            }

            if (_flushing && !_filteringCompleted) {
                _httpWriter.FilterIntegrated(false, iis7WorkerRequest);
                bufferedLength = _httpWriter.GetBufferedLength();
            }

            if (!_clientDisconnected && (bufferedLength > 0 || needPush)) {

                if (bufferedLength == 0 ) {
                    if (_httpWriter.IgnoringFurtherWrites) {
                        return;
                    }
                }

                // push HttpWriter buffers to worker request
                _httpWriter.Send(_wr);
                // push buffers through into native
                iis7WorkerRequest.PushResponseToNative();
                // dispose them (since they're copied or
                // owned by native request)
                _httpWriter.DisposeIntegratedBuffers();
            }
        }

        private void ClearNativeResponse(bool clearEntity, bool clearHeaders, IIS7WorkerRequest wr) {
            wr.ClearResponse(clearEntity, clearHeaders);
            if (clearEntity) {
                _httpWriter.ClearSubstitutionBlocks();
            }
        }

        private void SuppressCachingCookiesIfNecessary() {
            // MSRC 11855 (DevDiv 297240 / 362405)
            // We should suppress caching cookies if non-shareable cookies are
            // present in the response. Since these cookies can cary sensitive information, 
            // we should set Cache-Control: no-cache=set-cookie if there is such cookie
            // This prevents all well-behaved caches (both intermediary proxies and any local caches
            // on the client) from storing this sensitive information.
            // 
            // Additionally, we should not set this header during an SSL request, as certain versions
            // of IE don't handle it properly and simply refuse to render the page. More info:
            // http://blogs.msdn.com/b/ieinternals/archive/2009/10/02/internet-explorer-cannot-download-over-https-when-no-cache.aspx
            //
            // Finally, we don't need to set 'no-cache' if the response is not publicly cacheable,
            // as ASP.NET won't cache the response (due to the cookies) and proxies won't cache
            // the response (due to Cache-Control: private).
            // If _cachePolicy isn't set, then Cache.GetCacheability() will contruct a default one (which causes Cache-Control: private)
            if (!Request.IsSecureConnection && ContainsNonShareableCookies() && Cache.GetCacheability() == HttpCacheability.Public) {
                Cache.SetCacheability(HttpCacheability.NoCache, "Set-Cookie");
            }

            // if there are any cookies, do not kernel cache the response
            if (_cachePolicy != null && _cookies != null && _cookies.Count != 0) {
                _cachePolicy.SetHasSetCookieHeader();
                // In integrated mode, the cookies will eventually be sent to IIS via IIS7WorkerRequest.SetUnknownResponseHeader,
                // where we will disable both HTTP.SYS kernel cache and IIS user mode cache (DevDiv 113142 & 255268). In classic
                // mode, the cookies will be sent to IIS via ISAPIWorkerRequest.SendUnknownResponseHeader and 
                // ISAPIWorkerRequest.SendKnownResponseHeader (DevDiv 113142), where we also disables the kernel cache. So the 
                // call of DisableKernelCache below is not really needed.
                DisableKernelCache();
            }
        }

        private void EnsureSessionStateIfNecessary() {
            // Ensure the session state is in complete state before sending the response headers
            // Due to optimization and delay initialization sometimes we create and store the session state id in ReleaseSessionState.
            // But it's too late in case of Flush. Session state id must be written (if used) before sending the headers.
            if (AppSettings.EnsureSessionStateLockedOnFlush) {
                _context.EnsureSessionStateIfNecessary();
            }
        }
    }

    internal enum CacheDependencyType {
        Files,
        CacheItems,
        VirtualPaths
    }

    struct ResponseDependencyList {
        private ArrayList   _dependencies;
        private string[]    _dependencyArray;
        private DateTime    _oldestDependency;
        private string      _requestVirtualPath;

        internal void AddDependency(string item, string argname) {
            if (item == null) {
                throw new ArgumentNullException(argname);
            }

            _dependencyArray = null;

            if (_dependencies == null) {
                _dependencies = new ArrayList(1);
            }

            DateTime utcNow = DateTime.UtcNow;

            _dependencies.Add(new ResponseDependencyInfo(
                    new string[] {item}, utcNow));

            // _oldestDependency is initialized to MinValue and indicates that it must always be set
            if (_oldestDependency == DateTime.MinValue || utcNow < _oldestDependency)
                _oldestDependency = utcNow;
        }

        internal void AddDependencies(ArrayList items, string argname) {
            if (items == null) {
                throw new ArgumentNullException(argname);
            }

            string[] a = (string[]) items.ToArray(typeof(string));
            AddDependencies(a, argname, false);
        }

        internal void AddDependencies(string[] items, string argname) {
            AddDependencies(items, argname, true);
        }

        internal void AddDependencies(string[] items, string argname, bool cloneArray) {
            AddDependencies(items, argname, cloneArray, DateTime.UtcNow);
        }

        internal void AddDependencies(string[] items, string argname, bool cloneArray, string requestVirtualPath) {
            if (requestVirtualPath == null)
                throw new ArgumentNullException("requestVirtualPath");

            _requestVirtualPath = requestVirtualPath;
            AddDependencies(items, argname, cloneArray, DateTime.UtcNow);
        }

        internal void AddDependencies(string[] items, string argname, bool cloneArray, DateTime utcDepTime) {
            if (items == null) {
                throw new ArgumentNullException(argname);
            }

            string [] itemsLocal;

            if (cloneArray) {
                itemsLocal = (string[]) items.Clone();
            }
            else {
                itemsLocal = items;
            }

            foreach (string item in itemsLocal) {
                if (String.IsNullOrEmpty(item)) {
                    throw new ArgumentNullException(argname);
                }
            }

            _dependencyArray = null;

            if (_dependencies == null) {
                _dependencies = new ArrayList(1);
            }

            _dependencies.Add(new ResponseDependencyInfo(itemsLocal, utcDepTime));

            // _oldestDependency is initialized to MinValue and indicates that it must always be set
            if (_oldestDependency == DateTime.MinValue || utcDepTime < _oldestDependency)
                _oldestDependency = utcDepTime;
        }

        internal bool HasDependencies() {
            if (_dependencyArray == null && _dependencies == null)
                return false;

            return true;
        }

        internal string[] GetDependencies() {
            if (_dependencyArray == null && _dependencies != null) {
                int size = 0;
                foreach (ResponseDependencyInfo info in _dependencies) {
                    size += info.items.Length;
                }

                _dependencyArray = new string[size];

                int index = 0;
                foreach (ResponseDependencyInfo info in _dependencies) {
                    int length = info.items.Length;
                    Array.Copy(info.items, 0, _dependencyArray, index, length);
                    index += length;
                }
            }

            return _dependencyArray;
        }

        // The caller of this method must dispose the cache dependencies
        internal CacheDependency CreateCacheDependency(CacheDependencyType dependencyType, CacheDependency dependency) {
            if (_dependencies != null) {
                if (dependencyType == CacheDependencyType.Files
                    || dependencyType == CacheDependencyType.CacheItems) {
                    foreach (ResponseDependencyInfo info in _dependencies) {
                        CacheDependency dependencyOld = dependency;
                        try {
                            if (dependencyType == CacheDependencyType.Files) {
                                dependency = new CacheDependency(0, info.items, null, dependencyOld, info.utcDate);
                            }
                            else {
                                // We create a "public" CacheDepdency here, since the keys are for public items.
                                dependency = new CacheDependency(null, info.items, dependencyOld,
                                                                 DateTimeUtil.ConvertToLocalTime(info.utcDate));
                            }
                        }
                        finally {
                            if (dependencyOld != null) {
                                dependencyOld.Dispose();
                            }
                        }
                    }
                }
                else {
                    CacheDependency virtualDependency = null;
                    VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
                    if (vpp != null && _requestVirtualPath != null) {
                        virtualDependency = vpp.GetCacheDependency(_requestVirtualPath, GetDependencies(), _oldestDependency);
                    }
                    if (virtualDependency != null) {
                        AggregateCacheDependency tempDep = new AggregateCacheDependency();
                        tempDep.Add(virtualDependency);
                        if (dependency != null) {
                            tempDep.Add(dependency);
                        }
                        dependency = tempDep;
                    }
                }
            }

            return dependency;
        }
    }

    internal class ResponseDependencyInfo {
        internal readonly string[]    items;
        internal readonly DateTime    utcDate;

        internal ResponseDependencyInfo(string[] items, DateTime utcDate) {
            this.items = items;
            this.utcDate = utcDate;
        }
    }
}