forked from aspnet/AspNetWebStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpControllerHandler.cs
More file actions
775 lines (668 loc) · 35.6 KB
/
HttpControllerHandler.cs
File metadata and controls
775 lines (668 loc) · 35.6 KB
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Configuration;
using System.Web.Http.Controllers;
using System.Web.Http.ExceptionHandling;
using System.Web.Http.Hosting;
using System.Web.Http.Routing;
using System.Web.Http.WebHost.Properties;
using System.Web.Http.WebHost.Routing;
using System.Web.Routing;
namespace System.Web.Http.WebHost
{
/// <summary>
/// An <see cref="HttpTaskAsyncHandler"/> that uses an <see cref="HttpServer"/> to process ASP.NET requests asynchronously.
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This class is a coordinator, so this coupling is expected.")]
[SuppressMessage("Microsoft.Design", "CA1001:Implement IDisposable", Justification = "HttpMessageInvoker doesn’t have any resources of its own to dispose.")]
public class HttpControllerHandler : HttpTaskAsyncHandler
{
// See Microsoft.Owin.Host.SystemWeb.
internal static readonly string OwinEnvironmentHttpContextKey = "owin.Environment";
internal static readonly string OwinEnvironmentKey = "MS_OwinEnvironment";
private static readonly Lazy<Action<HttpContextBase>> _suppressRedirectAction =
new Lazy<Action<HttpContextBase>>(
() =>
{
// If the behavior is explicitly disabled, do nothing
if (!SuppressFormsAuthRedirectHelper.GetEnabled(WebConfigurationManager.AppSettings))
{
return httpContext => { };
}
return httpContext => httpContext.Response.SuppressFormsAuthenticationRedirect = true;
});
private static readonly Lazy<IHostBufferPolicySelector> _bufferPolicySelector =
new Lazy<IHostBufferPolicySelector>(() => GlobalConfiguration.Configuration.Services.GetHostBufferPolicySelector());
private static readonly Lazy<IExceptionHandler> _exceptionHandler = new Lazy<IExceptionHandler>(() =>
ExceptionServices.GetHandler(GlobalConfiguration.Configuration));
private static readonly Lazy<IExceptionLogger> _exceptionLogger = new Lazy<IExceptionLogger>(() =>
ExceptionServices.GetLogger(GlobalConfiguration.Configuration));
private static readonly Func<HttpRequestMessage, X509Certificate2> _retrieveClientCertificate = new Func<HttpRequestMessage, X509Certificate2>(RetrieveClientCertificate);
private readonly IHttpRouteData _routeData;
private readonly HttpMessageInvoker _server;
/// <summary>
/// Initializes a new instance of the <see cref="HttpControllerHandler"/> class.
/// </summary>
/// <param name="routeData">The route data.</param>
public HttpControllerHandler(RouteData routeData)
: this(routeData, GlobalConfiguration.DefaultServer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpControllerHandler"/> class.
/// </summary>
/// <param name="routeData">The route data.</param>
/// <param name="handler">The message handler to dispatch requests to.</param>
public HttpControllerHandler(RouteData routeData, HttpMessageHandler handler)
{
if (routeData == null)
{
throw Error.ArgumentNull("routeData");
}
if (handler == null)
{
throw Error.ArgumentNull("handler");
}
_routeData = new HostedHttpRouteData(routeData);
_server = new HttpMessageInvoker(handler);
}
public override Task ProcessRequestAsync(HttpContext context)
{
return ProcessRequestAsyncCore(new HttpContextWrapper(context));
}
internal async Task ProcessRequestAsyncCore(HttpContextBase contextBase)
{
HttpRequestMessage request = contextBase.GetHttpRequestMessage() ?? ConvertRequest(contextBase);
// Add route data
request.SetRouteData(_routeData);
CancellationToken cancellationToken = contextBase.Response.GetClientDisconnectedTokenWhenFixed();
HttpResponseMessage response = null;
try
{
response = await _server.SendAsync(request, cancellationToken);
await CopyResponseAsync(contextBase, request, response, _exceptionLogger.Value, _exceptionHandler.Value,
cancellationToken);
}
catch (OperationCanceledException)
{
// HttpTaskAsyncHandler treats a canceled task as an unhandled exception (logged to Application event
// log). Instead of returning a canceled task, abort the request and return a completed task.
contextBase.Request.Abort();
}
finally
{
// The other HttpTaskAsyncHandler is HttpRouteExceptionHandler; it has similar cleanup logic.
request.DisposeRequestResources();
request.Dispose();
if (response != null)
{
response.Dispose();
}
}
}
private static void CopyHeaders(HttpHeaders from, HttpContextBase to)
{
Contract.Assert(from != null);
Contract.Assert(to != null);
foreach (var header in from)
{
string name = header.Key;
foreach (var value in header.Value)
{
to.Response.AppendHeader(name, value);
}
}
}
private static void AddHeaderToHttpRequestMessage(HttpRequestMessage httpRequestMessage, string headerName, string[] headerValues)
{
Contract.Assert(httpRequestMessage != null);
Contract.Assert(headerName != null);
Contract.Assert(headerValues != null);
if (!httpRequestMessage.Headers.TryAddWithoutValidation(headerName, headerValues))
{
httpRequestMessage.Content.Headers.TryAddWithoutValidation(headerName, headerValues);
}
}
internal static async Task CopyResponseAsync(HttpContextBase httpContextBase, HttpRequestMessage request,
HttpResponseMessage response, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler,
CancellationToken cancellationToken)
{
Contract.Assert(httpContextBase != null);
Contract.Assert(request != null);
// A null response creates a 500 with no content
if (response == null)
{
SetEmptyErrorResponse(httpContextBase.Response);
return;
}
if (!await CopyResponseStatusAndHeadersAsync(httpContextBase, request, response, exceptionLogger,
cancellationToken))
{
return;
}
// TODO 335085: Consider this when coming up with our caching story
if (response.Headers.CacheControl == null)
{
// DevDiv2 #332323. ASP.NET by default always emits a cache-control: private header.
// However, we don't want requests to be cached by default.
// If nobody set an explicit CacheControl then explicitly set to no-cache to override the
// default behavior. This will cause the following response headers to be emitted:
// Cache-Control: no-cache
// Pragma: no-cache
// Expires: -1
httpContextBase.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
// Asynchronously write the response body. If there is no body, we use
// a completed task to share the Finally() below.
// The response-writing task will not fault -- it handles errors internally.
if (response.Content != null)
{
await WriteResponseContentAsync(httpContextBase, request, response, exceptionLogger, exceptionHandler, cancellationToken);
}
}
internal static HttpRequestMessage ConvertRequest(HttpContextBase httpContextBase)
{
return ConvertRequest(httpContextBase, _bufferPolicySelector.Value);
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Caller becomes owner")]
internal static HttpRequestMessage ConvertRequest(HttpContextBase httpContextBase, IHostBufferPolicySelector policySelector)
{
Contract.Assert(httpContextBase != null);
HttpRequestBase requestBase = httpContextBase.Request;
HttpMethod method = HttpMethodHelper.GetHttpMethod(requestBase.HttpMethod);
Uri uri = requestBase.Url;
HttpRequestMessage request = new HttpRequestMessage(method, uri);
// Choose a buffered or bufferless input stream based on user's policy
bool bufferInput = policySelector == null ? true : policySelector.UseBufferedInputStream(httpContextBase);
request.Content = GetStreamContent(requestBase, bufferInput);
foreach (string headerName in requestBase.Headers)
{
string[] values = requestBase.Headers.GetValues(headerName);
AddHeaderToHttpRequestMessage(request, headerName, values);
}
// Add context to enable route lookup later on
request.SetHttpContext(httpContextBase);
HttpRequestContext requestContext = new WebHostHttpRequestContext(httpContextBase, requestBase, request);
request.SetRequestContext(requestContext);
IDictionary httpContextItems = httpContextBase.Items;
// Add the OWIN environment, when available (such as when using the OWIN integrated pipeline HTTP module).
if (httpContextItems != null && httpContextItems.Contains(OwinEnvironmentHttpContextKey))
{
request.Properties.Add(OwinEnvironmentKey, httpContextItems[OwinEnvironmentHttpContextKey]);
}
// The following three properties are set for backwards compatibility only. The request context controls
// the behavior for all cases except when accessing the property directly by key.
// Add the retrieve client certificate delegate to the property bag to enable lookup later on
request.Properties.Add(HttpPropertyKeys.RetrieveClientCertificateDelegateKey, _retrieveClientCertificate);
// Add information about whether the request is local or not
request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy<bool>(() => requestBase.IsLocal));
// Add information about whether custom errors are enabled for this request or not
request.Properties.Add(HttpPropertyKeys.IncludeErrorDetailKey, new Lazy<bool>(() => !httpContextBase.IsCustomErrorEnabled));
return request;
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Caller becomes owner")]
private static HttpContent GetStreamContent(HttpRequestBase requestBase, bool bufferInput)
{
if (bufferInput)
{
return new LazyStreamContent(() =>
{
if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.None)
{
return new SeekableBufferedRequestStream(requestBase);
}
else if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Classic)
{
requestBase.InputStream.Position = 0;
return requestBase.InputStream;
}
else if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Buffered)
{
if (requestBase.GetBufferedInputStream().Position > 0)
{
// If GetBufferedInputStream() was completely read, we can continue accessing it via Request.InputStream.
// If it was partially read, accessing InputStream will throw, but at that point we have no
// way of recovering.
requestBase.InputStream.Position = 0;
return requestBase.InputStream;
}
return new SeekableBufferedRequestStream(requestBase);
}
else
{
Contract.Assert(requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Bufferless);
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
SRResources.RequestBodyAlreadyReadInMode,
ReadEntityBodyMode.Bufferless));
}
});
}
else
{
return new LazyStreamContent(() =>
{
if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.None)
{
return requestBase.GetBufferlessInputStream();
}
else if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Classic)
{
// The user intended that the request be read in a bufferless manner, but we are starting with a buffered stream.
// To maintain compatibility with legacy behavior, we'll throw in this case.
throw new InvalidOperationException(SRResources.RequestStreamCannotBeReadBufferless);
}
else if (requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Bufferless)
{
Stream bufferlessInputStream = requestBase.GetBufferlessInputStream();
if (bufferlessInputStream.Position > 0)
{
throw new InvalidOperationException(SRResources.RequestBodyAlreadyRead);
}
return bufferlessInputStream;
}
else
{
Contract.Assert(requestBase.ReadEntityBodyMode == ReadEntityBodyMode.Buffered);
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SRResources.RequestBodyAlreadyReadInMode, ReadEntityBodyMode.Buffered));
}
});
}
}
/// <summary>
/// Prevents the <see cref="T:System.Web.Security.FormsAuthenticationModule"/> from altering a 401 response to 302 by
/// setting <see cref="P:System.Web.HttpResponseBase.SuppressFormsAuthenticationRedirect" /> to <c>true</c> if available.
/// </summary>
/// <param name="httpContextBase">The HTTP context base.</param>
internal static void EnsureSuppressFormsAuthenticationRedirect(HttpContextBase httpContextBase)
{
Contract.Assert(httpContextBase != null);
// Only if the response is status code is 401
if (httpContextBase.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
_suppressRedirectAction.Value(httpContextBase);
}
}
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "unused", Justification = "unused variable necessary to call getter")]
private static Task WriteResponseContentAsync(HttpContextBase httpContextBase, HttpRequestMessage request,
HttpResponseMessage response, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler,
CancellationToken cancellationToken)
{
Contract.Assert(httpContextBase != null);
Contract.Assert(response != null);
Contract.Assert(request != null);
Contract.Assert(response.Content != null);
HttpResponseBase httpResponseBase = httpContextBase.Response;
HttpContent responseContent = response.Content;
CopyHeaders(responseContent.Headers, httpContextBase);
// PrepareHeadersAsync already evaluated the buffer policy.
bool isBuffered = httpResponseBase.BufferOutput;
return isBuffered
? WriteBufferedResponseContentAsync(httpContextBase, request, response, exceptionLogger, exceptionHandler, cancellationToken)
: WriteStreamedResponseContentAsync(httpContextBase, request, response, exceptionLogger, cancellationToken);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "All exceptions caught here become error responses")]
internal static async Task WriteStreamedResponseContentAsync(HttpContextBase httpContextBase,
HttpRequestMessage request, HttpResponseMessage response, IExceptionLogger exceptionLogger,
CancellationToken cancellationToken)
{
Contract.Assert(httpContextBase != null);
Contract.Assert(httpContextBase.Response != null);
Contract.Assert(request != null);
Contract.Assert(response != null);
Contract.Assert(response.Content != null);
Exception exception = null;
cancellationToken.ThrowIfCancellationRequested();
try
{
// Copy the HttpContent into the output stream asynchronously.
await response.Content.CopyToAsync(httpContextBase.Response.OutputStream);
return;
}
catch (OperationCanceledException)
{
// Propogate the canceled task without calling exception loggers.
throw;
}
catch (Exception ex)
{
exception = ex;
}
Contract.Assert(exception != null);
ExceptionContextCatchBlock catchBlock = WebHostExceptionCatchBlocks.HttpControllerHandlerStreamContent;
ExceptionContext exceptionContext = new ExceptionContext(exception, catchBlock, request, response);
await exceptionLogger.LogAsync(exceptionContext, cancellationToken);
// Streamed content may have been written and cannot be recalled.
// Our only choice is to abort the connection.
httpContextBase.Request.Abort();
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "continuation task owned by caller")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "All exceptions caught here become error responses")]
internal static async Task WriteBufferedResponseContentAsync(HttpContextBase httpContextBase,
HttpRequestMessage request, HttpResponseMessage response, IExceptionLogger exceptionLogger,
IExceptionHandler exceptionHandler, CancellationToken cancellationToken)
{
Contract.Assert(httpContextBase != null);
Contract.Assert(httpContextBase.Response != null);
Contract.Assert(request != null);
Contract.Assert(response != null);
Contract.Assert(response.Content != null);
HttpResponseBase httpResponseBase = httpContextBase.Response;
// Return a task that writes the response body asynchronously.
// We guarantee we will handle all error responses internally
// and always return a non-faulted task, except for custom error handlers that choose to propagate these
// exceptions.
ExceptionDispatchInfo exceptionInfo;
cancellationToken.ThrowIfCancellationRequested();
try
{
// Copy the HttpContent into the output stream asynchronously.
await response.Content.CopyToAsync(httpResponseBase.OutputStream);
return;
}
catch (OperationCanceledException)
{
// Propogate the canceled task without calling exception loggers or handlers.
throw;
}
catch (Exception exception)
{
// Can't use await inside a catch block
exceptionInfo = ExceptionDispatchInfo.Capture(exception);
}
Debug.Assert(exceptionInfo.SourceException != null);
// If we were using a buffered stream, we can still set the headers and status code, and we can create an
// error response with the exception.
// We create a continuation task to write an error response that will run after returning from this Catch()
// but before other continuations the caller appends to this task.
// The error response writing task handles errors internally and will not show as faulted, except for
// custom error handlers that choose to propagate these exceptions.
ExceptionContextCatchBlock catchBlock = WebHostExceptionCatchBlocks.HttpControllerHandlerBufferContent;
if (!await CopyErrorResponseAsync(catchBlock, httpContextBase, request, response,
exceptionInfo.SourceException, exceptionLogger, exceptionHandler, cancellationToken))
{
exceptionInfo.Throw();
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "All exceptions caught here become error responses")]
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "errorResponse gets disposed in the async continuation")]
internal static async Task<bool> CopyErrorResponseAsync(ExceptionContextCatchBlock catchBlock,
HttpContextBase httpContextBase, HttpRequestMessage request, HttpResponseMessage response,
Exception exception, IExceptionLogger exceptionLogger, IExceptionHandler exceptionHandler,
CancellationToken cancellationToken)
{
Contract.Assert(httpContextBase != null);
Contract.Assert(httpContextBase.Response != null);
Contract.Assert(request != null);
Contract.Assert(exception != null);
Contract.Assert(catchBlock != null);
Contract.Assert(catchBlock.CallsHandler);
HttpResponseBase httpResponseBase = httpContextBase.Response;
HttpResponseMessage errorResponse = null;
HttpResponseException responseException = exception as HttpResponseException;
// Ensure all headers and content are cleared to eliminate any partial results.
ClearContentAndHeaders(httpResponseBase);
// If the exception we are handling is HttpResponseException,
// that becomes the error response.
if (responseException != null)
{
errorResponse = responseException.Response;
}
else
{
ExceptionContext exceptionContext = new ExceptionContext(exception, catchBlock, request)
{
Response = response
};
await exceptionLogger.LogAsync(exceptionContext, cancellationToken);
errorResponse = await exceptionHandler.HandleAsync(exceptionContext, cancellationToken);
if (errorResponse == null)
{
return false;
}
}
Contract.Assert(errorResponse != null);
if (!await CopyResponseStatusAndHeadersAsync(httpContextBase, request, errorResponse, exceptionLogger,
cancellationToken))
{
// Don't rethrow the original exception unless explicitly requested to do so. In this case, the
// exception handler indicated it wanted to handle the exception; it simply failed create a stable
// response to send.
return true;
}
// The error response may return a null content if content negotiation
// fails to find a formatter, or this may be an HttpResponseException without
// content. In either case, cleanup and return a completed task.
if (errorResponse.Content == null)
{
errorResponse.Dispose();
return true;
}
CopyHeaders(errorResponse.Content.Headers, httpContextBase);
await WriteErrorResponseContentAsync(httpResponseBase, request, errorResponse, cancellationToken,
exceptionLogger);
return true;
}
private static async Task WriteErrorResponseContentAsync(HttpResponseBase httpResponseBase,
HttpRequestMessage request, HttpResponseMessage errorResponse, CancellationToken cancellationToken,
IExceptionLogger exceptionLogger)
{
HttpRequestMessage ignoreUnused = request;
try
{
Exception exception = null;
cancellationToken.ThrowIfCancellationRequested();
try
{
// Asynchronously write the content of the new error HttpResponseMessage
await errorResponse.Content.CopyToAsync(httpResponseBase.OutputStream);
return;
}
catch (OperationCanceledException)
{
// Propogate the canceled task without calling exception loggers.
throw;
}
catch (Exception ex)
{
exception = ex;
}
Contract.Assert(exception != null);
ExceptionContext exceptionContext = new ExceptionContext(exception,
WebHostExceptionCatchBlocks.HttpControllerHandlerBufferError, request, errorResponse);
await exceptionLogger.LogAsync(exceptionContext, cancellationToken);
// Failure writing the error response. Likely cause is a formatter
// serialization exception. Create empty error response and
// return a non-faulted task.
SetEmptyErrorResponse(httpResponseBase);
}
finally
{
// Dispose the temporary HttpResponseMessage carrying the error response
errorResponse.Dispose();
}
}
private static async Task<bool> CopyResponseStatusAndHeadersAsync(HttpContextBase httpContextBase,
HttpRequestMessage request, HttpResponseMessage response, IExceptionLogger exceptionLogger,
CancellationToken cancellationToken)
{
Contract.Assert(httpContextBase != null);
HttpResponseBase httpResponseBase = httpContextBase.Response;
httpResponseBase.StatusCode = (int)response.StatusCode;
httpResponseBase.StatusDescription = response.ReasonPhrase;
httpResponseBase.TrySkipIisCustomErrors = true;
EnsureSuppressFormsAuthenticationRedirect(httpContextBase);
if (!await PrepareHeadersAsync(httpResponseBase, request, response, exceptionLogger, cancellationToken))
{
return false;
}
CopyHeaders(response.Headers, httpContextBase);
return true;
}
// Prepares Content-Length and Transfer-Encoding headers.
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "unused", Justification = "unused variable necessary to call getter")]
internal static async Task<bool> PrepareHeadersAsync(HttpResponseBase responseBase, HttpRequestMessage request,
HttpResponseMessage response, IExceptionLogger exceptionLogger, CancellationToken cancellationToken)
{
Contract.Assert(response != null);
HttpResponseHeaders responseHeaders = response.Headers;
Contract.Assert(responseHeaders != null);
HttpContent content = response.Content;
bool isTransferEncodingChunked = responseHeaders.TransferEncodingChunked == true;
HttpHeaderValueCollection<TransferCodingHeaderValue> transferEncoding = responseHeaders.TransferEncoding;
if (content != null)
{
HttpContentHeaders contentHeaders = content.Headers;
Contract.Assert(contentHeaders != null);
if (isTransferEncodingChunked)
{
// According to section 4.4 of the HTTP 1.1 spec, HTTP responses that use chunked transfer
// encoding must not have a content length set. Chunked should take precedence over content
// length in this case because chunked is always set explicitly by users while the Content-Length
// header can be added implicitly by System.Net.Http.
contentHeaders.ContentLength = null;
}
else
{
Exception exception = null;
// Copy the response content headers only after ensuring they are complete.
// We ask for Content-Length first because HttpContent lazily computes this
// and only afterwards writes the value into the content headers.
try
{
var unused = contentHeaders.ContentLength;
}
catch (Exception ex)
{
exception = ex;
}
if (exception != null)
{
ExceptionContext exceptionContext = new ExceptionContext(exception,
WebHostExceptionCatchBlocks.HttpControllerHandlerComputeContentLength, request, response);
await exceptionLogger.LogAsync(exceptionContext, cancellationToken);
SetEmptyErrorResponse(responseBase);
return false;
}
}
// Select output buffering based on the user-controlled buffering policy
bool isBuffered = _bufferPolicySelector.Value != null ?
_bufferPolicySelector.Value.UseBufferedOutputStream(response) : true;
responseBase.BufferOutput = isBuffered;
}
// Ignore the Transfer-Encoding header if it is just "chunked"; the host will provide it when no
// Content-Length is present and BufferOutput is disabled (and this method guarantees those conditions).
// HttpClient sets this header when it receives chunked content, but HttpContent does not include the
// frames. The ASP.NET contract is to set this header only when writing chunked frames to the stream.
// A Web API caller who desires custom framing would need to do a different Transfer-Encoding (such as
// "identity, chunked").
if (isTransferEncodingChunked && transferEncoding.Count == 1)
{
transferEncoding.Clear();
// In the case of a conflict between a Transfer-Encoding: chunked header and the output buffering
// policy, honor the Transnfer-Encoding: chunked header and ignore the buffer policy.
// If output buffering is not disabled, ASP.NET will not write the TransferEncoding: chunked header.
responseBase.BufferOutput = false;
}
return true;
}
private static void ClearContentAndHeaders(HttpResponseBase httpResponseBase)
{
httpResponseBase.Clear();
// Despite what the documentation indicates, calling Clear on its own doesn't fully clear the headers.
httpResponseBase.ClearHeaders();
}
private static void SetEmptyErrorResponse(HttpResponseBase httpResponseBase)
{
ClearContentAndHeaders(httpResponseBase);
httpResponseBase.StatusCode = (int)HttpStatusCode.InternalServerError;
httpResponseBase.SuppressContent = true;
}
private static X509Certificate2 RetrieveClientCertificate(HttpRequestMessage request)
{
if (request == null)
{
throw Error.ArgumentNull("request");
}
X509Certificate2 result = null;
HttpContextBase httpContextBase = request.GetHttpContext();
if (httpContextBase != null)
{
if (httpContextBase.Request.ClientCertificate.Certificate != null && httpContextBase.Request.ClientCertificate.Certificate.Length > 0)
{
result = new X509Certificate2(httpContextBase.Request.ClientCertificate.Certificate);
}
}
return result;
}
private class DelegatingStreamContent : StreamContent
{
public DelegatingStreamContent(Stream stream)
: base(stream)
{
}
public Task WriteToStreamAsync(Stream stream, TransportContext context)
{
return SerializeToStreamAsync(stream, context);
}
public Task<Stream> GetContentReadStreamAsync()
{
return CreateContentReadStreamAsync();
}
protected override bool TryComputeLength(out long length)
{
// Do not attempt to calculate length because SeekableBufferedRequestStream (for example)
// may report 0 until the underlying Stream has been read to end.
length = 0L;
return false;
}
}
private class LazyStreamContent : HttpContent
{
private readonly Func<Stream> _getStream;
private DelegatingStreamContent _streamContent;
public LazyStreamContent(Func<Stream> getStream)
{
_getStream = getStream;
}
private DelegatingStreamContent StreamContent
{
get
{
if (_streamContent == null)
{
_streamContent = new DelegatingStreamContent(_getStream());
}
return _streamContent;
}
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return StreamContent.WriteToStreamAsync(stream, context);
}
protected override Task<Stream> CreateContentReadStreamAsync()
{
return StreamContent.GetContentReadStreamAsync();
}
protected override bool TryComputeLength(out long length)
{
// Do not attempt to calculate length because SeekableBufferedRequestStream (for example)
// may report 0 until the underlying Stream has been read to end.
length = 0L;
return false;
}
}
}
}