-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathHttpResponse.cs
3709 lines (3093 loc) · 142 KB
/
HttpResponse.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// <copyright file="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) {
bool setHeader = true;
if (AppSettings.AvoidDuplicatedSetCookie) {
if(!cookie.IsInResponseHeader) {
cookie.IsInResponseHeader = true;
}
else {
setHeader = false;
}
}
if(setHeader) {
// 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;
if(AppSettings.AvoidDuplicatedSetCookie) {
cookie.IsInResponseHeader = true;
}
}
_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 sync 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 sync 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];
}