File: HostedHttpContext.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (875 lines) | stat: -rw-r--r-- 34,875 bytes parent folder | download | duplicates (7)
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
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Activation
{
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Net.WebSockets;
    using System.Runtime;
    using System.Security;
    using System.Security.Authentication.ExtendedProtection;
    using System.Security.Permissions;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Diagnostics;
    using System.ServiceModel.Security;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Management;
    using System.Web.WebSockets;

    class HostedHttpContext : HttpRequestContext
    {
        HostedRequestContainer requestContainer;
        HostedHttpRequestAsyncResult result;
        TaskCompletionSource<object> webSocketWaitingTask;
        RemoteEndpointMessageProperty remoteEndpointMessageProperty;
        TaskCompletionSource<WebSocketContext> webSocketContextTaskSource;

        int impersonationReleased = 0;

        public HostedHttpContext(HttpChannelListener listener, HostedHttpRequestAsyncResult result)
            : base(listener, null, result.EventTraceActivity)
        {
            AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

            this.result = result;
            result.AddRefForImpersonation();
        }

        public override string HttpMethod
        {
            get
            {
                return result.GetHttpMethod();
            }
        }

        internal void CompleteWithException(Exception ex)
        {
            Fx.Assert(ex != null, "ex should not be null.");
            this.result.CompleteOperation(ex);
        }

        protected override SecurityMessageProperty OnProcessAuthentication()
        {
            return Listener.ProcessAuthentication(this.result);
        }

        protected override HttpStatusCode ValidateAuthentication()
        {
            return Listener.ValidateAuthentication(this.result);
        }

        // Accessing the headers of an already replied HttpRequest instance causes an Access Violation in hosted mode.
        // In one-way scenarios, reply happens before the user gets the message. That's why we are disabling all access
        // to HostedRequestContainer (CSDMain 34014).
        void CloseHostedRequestContainer()
        {
            // RequestContext.RequestMessage property can throw rather than create a message.
            // This means we never created a message and never cached the IIS properties.
            // At this point the user may return a reply, so requestContainer is allowed to be null.
            if (this.requestContainer != null)
            {
                this.requestContainer.Close();
                this.requestContainer = null;
            }
        }

        protected override Task<WebSocketContext> AcceptWebSocketCore(HttpResponseMessage response, string protocol)
        {
            this.BeforeAcceptWebSocket(response);
            this.webSocketContextTaskSource = new TaskCompletionSource<WebSocketContext>();
            this.result.Application.Context.AcceptWebSocketRequest(PostAcceptWebSocket, new AspNetWebSocketOptions() { SubProtocol = protocol });
            this.result.OnReplySent();
            return this.webSocketContextTaskSource.Task;
        }

        protected override void OnAcceptWebSocketSuccess(WebSocketContext context, HttpRequestMessage requestMessage)
        {
            // ASP.NET owns the WebSocket object and needs it during the cleanup process. We should not dispose the WebSocket in WCF layer.
            base.OnAcceptWebSocketSuccess(context, this.remoteEndpointMessageProperty, null, false, requestMessage);
        }

        void BeforeAcceptWebSocket(HttpResponseMessage response)
        {
            this.SetRequestContainer(new HostedRequestContainer(this.result));
            string address = string.Empty;
            int port = 0;

            if (this.requestContainer.TryGetAddressAndPort(out address, out port))
            {
                this.remoteEndpointMessageProperty = new RemoteEndpointMessageProperty(address, port);
            }

            this.CloseHostedRequestContainer();

            HostedHttpContext.AppendHeaderFromHttpResponseMessageToResponse(response, this.result);
        }

        Task PostAcceptWebSocket(AspNetWebSocketContext context)
        {
            this.webSocketWaitingTask = new TaskCompletionSource<object>();
            this.WebSocketChannel.Closed += new EventHandler(this.FinishWebSocketWaitingTask);
            this.webSocketContextTaskSource.SetResult(context);
            return webSocketWaitingTask.Task;
        }

        static void AppendHeaderFromHttpResponseMessageToResponse(HttpResponseMessage response, HostedHttpRequestAsyncResult result)
        {
            HostedHttpContext.AppendHeaderToResponse(response.Headers, result);
            if (response.Content != null)
            {
                HostedHttpContext.AppendHeaderToResponse(response.Content.Headers, result);
            }
        }

        static void AppendHeaderToResponse(HttpHeaders headers, HostedHttpRequestAsyncResult result)
        {
            foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
            {
                foreach (string value in header.Value)
                {
                    result.AppendHeader(header.Key, value);
                }
            }
        }

        void FinishWebSocketWaitingTask(object sender, EventArgs args)
        {
            this.webSocketWaitingTask.TrySetResult(null);
        }

        public override bool IsWebSocketRequest
        {
            get
            {
                return this.result.IsWebSocketRequest;
            }
        }

        protected override void OnReply(Message message, TimeSpan timeout)
        {
            this.CloseHostedRequestContainer();
            base.OnReply(message, timeout);
        }

        protected override IAsyncResult OnBeginReply(
            Message message, TimeSpan timeout, AsyncCallback callback, object state)
        {
            this.CloseHostedRequestContainer();
            return base.OnBeginReply(message, timeout, callback, state);
        }

        protected override void OnAbort()
        {
            base.OnAbort();
            result.Abort();
        }

        protected override void Cleanup()
        {
            base.Cleanup();

            if (Interlocked.Increment(ref this.impersonationReleased) == 1)
            {
                this.result.ReleaseImpersonation();
            }
        }

        protected override HttpInput GetHttpInput()
        {
            return new HostedHttpInput(this);
        }

        public override HttpOutput GetHttpOutput(Message message)
        {
            HttpInput httpInput = this.GetHttpInput(false);

            // work around http.sys keep alive bug with chunked requests, see MB 49676, this is fixed in Vista
            if ((httpInput != null && httpInput.ContentLength == -1 && !OSEnvironmentHelper.IsVistaOrGreater) || !this.KeepAliveEnabled)
            {
                result.SetConnectionClose();
            }

            ICompressedMessageEncoder compressedMessageEncoder = this.Listener.MessageEncoderFactory.Encoder as ICompressedMessageEncoder;
            if (compressedMessageEncoder != null && compressedMessageEncoder.CompressionEnabled)
            {
                string acceptEncoding = this.result.GetAcceptEncoding();
                compressedMessageEncoder.AddCompressedMessageProperties(message, acceptEncoding);
            }

            return new HostedRequestHttpOutput(result, Listener, message, this);
        }

        protected override void OnClose(TimeSpan timeout)
        {
            base.OnClose(timeout);
            result.OnReplySent();
        }

        void SetRequestContainer(HostedRequestContainer requestContainer)
        {
            this.requestContainer = requestContainer;
        }

        class HostedHttpInput : HttpInput
        {
            int contentLength;
            string contentType;
            HostedHttpContext hostedHttpContext;
            byte[] preReadBuffer;

            public HostedHttpInput(HostedHttpContext hostedHttpContext)
                : base(hostedHttpContext.Listener, true, hostedHttpContext.Listener.IsChannelBindingSupportEnabled)
            {
                AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

                this.hostedHttpContext = hostedHttpContext;

                EnvelopeVersion envelopeVersion = hostedHttpContext.Listener.MessageEncoderFactory.Encoder.MessageVersion.Envelope;

                // MB#29602, perf optimization
                if (envelopeVersion == EnvelopeVersion.Soap11)
                {
                    // For soap 1.1, use headers collection to get content-type since we need to pull in the headers 
                    // collection for SOAP-Action anyways
                    this.contentType = hostedHttpContext.result.GetContentType();
                }
                else
                {
                    // For soap 1.2, the we pull the action header from the content-type, so don't access the headers
                    // and just use the typed property. For other versions, we shouldn't need the headers up front.
                    this.contentType = hostedHttpContext.result.GetContentTypeFast();
                }

                this.contentLength = hostedHttpContext.result.GetContentLength();

                // MB#34947: System.Web signals chunked as 0 as well so the only way we can
                // differentiate is by reading ahead
                if (this.contentLength == 0)
                {
                    preReadBuffer = hostedHttpContext.result.GetPrereadBuffer(ref this.contentLength);
                }
            }

            public override long ContentLength
            {
                get
                {
                    return this.contentLength;
                }
            }

            protected override string ContentTypeCore
            {
                get
                {
                    return this.contentType;
                }
            }

            protected override bool HasContent
            {
                get { return (this.preReadBuffer != null || this.ContentLength > 0); }
            }

            protected override string SoapActionHeader
            {
                get
                {
                    return hostedHttpContext.result.GetSoapAction();
                }
            }

            protected override ChannelBinding ChannelBinding
            {
                get
                {
                    return ChannelBindingUtility.DuplicateToken(hostedHttpContext.result.GetChannelBinding());
                }
            }

            protected override void AddProperties(Message message)
            {
                HostedRequestContainer requestContainer = new HostedRequestContainer(this.hostedHttpContext.result);

                HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty(requestContainer);

                requestProperty.Method = this.hostedHttpContext.HttpMethod;

                // Uri.Query always includes the '?'
                if (this.hostedHttpContext.result.RequestUri.Query.Length > 1)
                {
                    requestProperty.QueryString = this.hostedHttpContext.result.RequestUri.Query.Substring(1);
                }

                message.Properties.Add(HttpRequestMessageProperty.Name, requestProperty);

                message.Properties.Add(HostingMessageProperty.Name, CreateMessagePropertyFromHostedResult(this.hostedHttpContext.result));
                message.Properties.Via = this.hostedHttpContext.result.RequestUri;

                RemoteEndpointMessageProperty remoteEndpointProperty = new RemoteEndpointMessageProperty(requestContainer);
                message.Properties.Add(RemoteEndpointMessageProperty.Name, remoteEndpointProperty);

                this.hostedHttpContext.SetRequestContainer(requestContainer);
            }

            public override void ConfigureHttpRequestMessage(HttpRequestMessage message)
            {
                message.Method = new HttpMethod(this.hostedHttpContext.result.GetHttpMethod());
                message.RequestUri = this.hostedHttpContext.result.RequestUri;
                foreach (string webHeaderKey in this.hostedHttpContext.result.Application.Context.Request.Headers.Keys)
                {
                    message.AddHeader(webHeaderKey, this.hostedHttpContext.result.Application.Context.Request.Headers[webHeaderKey]);
                }

                HostedRequestContainer requestContainer = new HostedRequestContainer(this.hostedHttpContext.result);
                RemoteEndpointMessageProperty remoteEndpointProperty = new RemoteEndpointMessageProperty(requestContainer);
                message.Properties.Add(RemoteEndpointMessageProperty.Name, remoteEndpointProperty);
            }

            [Fx.Tag.SecurityNote(Critical = "Calls critical .ctor(HostedImpersonationContext)",
                Safe = "Only accepts the incoming context from HostedHttpRequestAsyncResult which stores the context in a critical field")]
            [SecuritySafeCritical]
            static HostingMessageProperty CreateMessagePropertyFromHostedResult(HostedHttpRequestAsyncResult result)
            {
                return new HostingMessageProperty(result);
            }

            protected override Stream GetInputStream()
            {
                if (this.preReadBuffer != null)
                {
                    return new HostedInputStream(this.hostedHttpContext, this.preReadBuffer);
                }
                else
                {
                    return new HostedInputStream(this.hostedHttpContext);
                }
            }

            class HostedInputStream : HttpDelayedAcceptStream
            {
                HostedHttpRequestAsyncResult result;

                public HostedInputStream(HostedHttpContext hostedContext)
                    : base(hostedContext.result.GetInputStream())
                {
                    AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();
                    this.result = hostedContext.result;
                }

                public HostedInputStream(HostedHttpContext hostedContext, byte[] preReadBuffer)
                    : base(new PreReadStream(hostedContext.result.GetInputStream(), preReadBuffer))
                {
                    AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();
                    this.result = hostedContext.result;
                }

                public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
                {
                    if (!this.result.TryStartStreamedRead())
                    {
                        throw FxTrace.Exception.AsError(new CommunicationObjectAbortedException(SR.RequestContextAborted));
                    }

                    bool throwing = true;

                    try
                    {
                        IAsyncResult result = base.BeginRead(buffer, offset, count, callback, state);
                        throwing = false;
                        return result;
                    }
                    catch (HttpException hostedException)
                    {
                        throw FxTrace.Exception.AsError(CreateCommunicationException(hostedException));
                    }
                    finally
                    {
                        if (throwing)
                        {
                            this.result.SetStreamedReadFinished();
                        }
                    }
                }

                public override int EndRead(IAsyncResult result)
                {
                    try
                    {
                        return base.EndRead(result);
                    }
                    catch (HttpException hostedException)
                    {
                        throw FxTrace.Exception.AsError(CreateCommunicationException(hostedException));
                    }
                    finally
                    {
                        this.result.SetStreamedReadFinished();
                    }
                }

                public override int Read(byte[] buffer, int offset, int count)
                {
                    if (!this.result.TryStartStreamedRead())
                    {
                        throw FxTrace.Exception.AsError(new CommunicationObjectAbortedException(SR.RequestContextAborted));
                    }

                    try
                    {
                        return base.Read(buffer, offset, count);
                    }
                    catch (HttpException hostedException)
                    {
                        throw FxTrace.Exception.AsError(CreateCommunicationException(hostedException));
                    }
                    finally
                    {
                        this.result.SetStreamedReadFinished();
                    }
                }

                // Wraps HttpException as inner exception in CommunicationException or ProtocolException (which derives from CommunicationException)
                static Exception CreateCommunicationException(HttpException hostedException)
                {
                    if (hostedException.WebEventCode == WebEventCodes.RuntimeErrorPostTooLarge)
                    {
                        // This HttpException is thrown if greater than httpRuntime/maxRequestLength bytes have been read from the stream.
                        // Note that this code path can only be hit when GetBufferedInputStream() is called in HostedHttpRequestAsyncResult.GetInputStream(), which only
                        // happens when an Http Module which is executed before the WCF Http Handler has accessed the request stream via GetBufferedInputStream().
                        // This is the only case that throws because GetBufferlessInputStream(true) ignores maxRequestLength, and InputStream property throws when invoked, not when stream is read.
                        return HttpInput.CreateHttpProtocolException(SR.Hosting_MaxRequestLengthExceeded, HttpStatusCode.RequestEntityTooLarge, null, hostedException);
                    }
                    else
                    {
                        // This HttpException is thrown if client disconnects and a read operation is invoked on the stream.
                        return new CommunicationException(hostedException.Message, hostedException);
                    }

                }
            }
        }

        class HostedRequestHttpOutput : HttpOutput
        {
            HostedHttpRequestAsyncResult result;
            HostedHttpContext context;
            string mimeVersion;
            string contentType;
            int statusCode;
            bool isSettingMimeHeader = false;
            bool isSettingContentType = false;

            public HostedRequestHttpOutput(HostedHttpRequestAsyncResult result, IHttpTransportFactorySettings settings,
                Message message, HostedHttpContext context)
                : base(settings, message, false, false)
            {
                AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

                this.result = result;
                this.context = context;

                if (TransferModeHelper.IsResponseStreamed(settings.TransferMode))
                    result.SetTransferModeToStreaming();

                if (message.IsFault)
                {
                    this.statusCode = (int)HttpStatusCode.InternalServerError;
                }
                else
                {
                    this.statusCode = (int)HttpStatusCode.OK;
                }
            }

            protected override Stream GetOutputStream()
            {
                return new HostedResponseOutputStream(this.result, this.context);
            }

            protected override void AddHeader(string name, string value)
            {
                this.result.AppendHeader(name, value);
            }

            protected override void AddMimeVersion(string version)
            {
                if (!isSettingMimeHeader)
                {
                    this.mimeVersion = version;
                }
                else
                {
                    this.result.AppendHeader(HttpChannelUtilities.MIMEVersionHeader, this.mimeVersion);
                }
            }

            protected override void SetContentType(string contentType)
            {
                if (!this.isSettingContentType)
                {
                    this.contentType = contentType;
                }
                else
                {
                    this.result.SetContentType(contentType);
                }
            }

            protected override void SetContentEncoding(string contentEncoding)
            {
                this.result.AppendHeader(HttpChannelUtilities.ContentEncodingHeader, contentEncoding);
            }

            protected override void SetContentLength(int contentLength)
            {
                this.result.AppendHeader("content-length", contentLength.ToString(CultureInfo.InvariantCulture));
            }

            protected override void SetStatusCode(HttpStatusCode statusCode)
            {
                this.result.SetStatusCode((int)statusCode);
            }

            protected override void SetStatusDescription(string statusDescription)
            {
                this.result.SetStatusDescription(statusDescription);
            }

            protected override bool PrepareHttpSend(Message message)
            {
                bool retValue = base.PrepareHttpSend(message);
                object property;

                bool httpMethodIsHead = string.Compare(this.context.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase) == 0;
                if (httpMethodIsHead)
                {
                    retValue = true;
                }

                if (message.Properties.TryGetValue(HttpResponseMessageProperty.Name, out property))
                {
                    HttpResponseMessageProperty responseProperty = (HttpResponseMessageProperty)property;

                    if (responseProperty.SuppressPreamble)
                    {
                        return retValue || responseProperty.SuppressEntityBody;
                    }

                    this.SetStatusCode(responseProperty.StatusCode);
                    if (responseProperty.StatusDescription != null)
                    {
                        this.SetStatusDescription(responseProperty.StatusDescription);
                    }

                    WebHeaderCollection responseHeaders = responseProperty.Headers;
                    for (int i = 0; i < responseHeaders.Count; i++)
                    {
                        string name = responseHeaders.Keys[i];
                        string value = responseHeaders[i];
                        if (string.Compare(name, "content-type", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            this.contentType = value;
                        }
                        else if (string.Compare(name, HttpChannelUtilities.MIMEVersionHeader, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            this.mimeVersion = value;
                        }
                        else if (string.Compare(name, "content-length", StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            int contentLength = -1;
                            if (httpMethodIsHead &&
                                int.TryParse(value, out contentLength))
                            {
                                this.SetContentLength(contentLength);
                            }
                        }
                        else
                        {
                            this.AddHeader(name, value);
                        }
                    }
                    if (responseProperty.SuppressEntityBody)
                    {
                        contentType = null;
                        retValue = true;
                    }
                }

                else
                {
                    this.SetStatusCode((HttpStatusCode)statusCode);
                }

                if (contentType != null && contentType.Length != 0)
                {
                    if (this.CanSendCompressedResponses)
                    {
                        string contentEncoding;
                        if (HttpChannelUtilities.GetHttpResponseTypeAndEncodingForCompression(ref contentType, out contentEncoding))
                        {
                            result.SetContentEncoding(contentEncoding);
                        }
                    }

                    this.isSettingContentType = true;
                    this.SetContentType(contentType);
                }

                if (this.mimeVersion != null)
                {
                    this.isSettingMimeHeader = true;
                    this.AddMimeVersion(this.mimeVersion);
                }

                return retValue;
            }

            protected override void PrepareHttpSendCore(HttpResponseMessage message)
            {
                result.SetStatusCode((int)message.StatusCode);
                if (message.ReasonPhrase != null)
                {
                    result.SetStatusDescription(message.ReasonPhrase);
                }
                HostedHttpContext.AppendHeaderFromHttpResponseMessageToResponse(message, this.result);
            }

            class HostedResponseOutputStream : BytesReadPositionStream
            {
                HostedHttpContext context;
                HostedHttpRequestAsyncResult result;

                public HostedResponseOutputStream(HostedHttpRequestAsyncResult result, HostedHttpContext context)
                    : base(result.GetOutputStream())
                {
                    this.context = context;
                    this.result = result;
                }

                public override void Close()
                {
                    try
                    {
                        base.Close();
                    }
                    catch (Exception e)
                    {
                        CheckWrapThrow(e);
                        throw;
                    }
                    finally
                    {
                        result.OnReplySent();
                    }
                }

                public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
                {
                    try
                    {
                        return base.BeginWrite(buffer, offset, count, callback, state);
                    }
                    catch (Exception e)
                    {
                        CheckWrapThrow(e);
                        throw;
                    }
                }

                public override void EndWrite(IAsyncResult result)
                {
                    try
                    {
                        base.EndWrite(result);
                    }
                    catch (Exception e)
                    {
                        CheckWrapThrow(e);
                        throw;
                    }
                }

                public override void Write(byte[] buffer, int offset, int count)
                {
                    try
                    {
                        base.Write(buffer, offset, count);
                    }
                    catch (Exception e)
                    {
                        CheckWrapThrow(e);
                        throw;
                    }
                }

                void CheckWrapThrow(Exception e)
                {
                    if (!Fx.IsFatal(e))
                    {
                        if (e is HttpException)
                        {
                            if (this.context.Aborted)
                            {
                                throw FxTrace.Exception.AsError(
                                    new CommunicationObjectAbortedException(SR.RequestContextAborted, e));
                            }
                            else
                            {
                                throw FxTrace.Exception.AsError(new CommunicationException(e.Message, e));
                            }
                        }
                        else if (this.context.Aborted)
                        {
                            // See VsWhidbey (594450)
                            if (DiagnosticUtility.ShouldTraceError)
                            {
                                TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.RequestContextAbort, SR.TraceCodeRequestContextAbort, this, e);
                            }

                            throw FxTrace.Exception.AsError(new CommunicationObjectAbortedException(SR.RequestContextAborted));
                        }
                    }
                }
            }
        }

        class HostedRequestContainer : RemoteEndpointMessageProperty.IRemoteEndpointProvider, HttpRequestMessageProperty.IHttpHeaderProvider
        {
            volatile bool isClosed;
            HostedHttpRequestAsyncResult result;
            object thisLock;

            public HostedRequestContainer(HostedHttpRequestAsyncResult result)
            {
                AspNetPartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

                this.result = result;
                this.thisLock = new object();
            }

            object ThisLock
            {
                get
                {
                    return this.thisLock;
                }
            }

            // IIS properties are not valid once the reply occurs.
            // Close invalidates all access to these properties.
            public void Close()
            {
                lock (this.ThisLock)
                {
                    this.isClosed = true;
                }
            }


            [Fx.Tag.SecurityNote(Critical = "Calls getters with LinkDemands in ASP .NET objects",
                Safe = "Does not leak control or mutable/harmful data, no potential for harm")]
            [SecuritySafeCritical]
            void HttpRequestMessageProperty.IHttpHeaderProvider.CopyHeaders(WebHeaderCollection headers)
            {
                if (!this.isClosed)
                {
                    lock (this.ThisLock)
                    {
                        if (!this.isClosed)
                        {
                            HttpChannelUtilities.CopyHeadersToNameValueCollection(this.result.Application.Request.Headers, headers);                            
                        }
                    }
                }
            }

            [Fx.Tag.SecurityNote(Critical = "Calls getters with LinkDemands in ASP .NET objects",
                Safe = "Does not leak control or mutable/harmful data, no potential for harm")]
            [SecuritySafeCritical]
            string RemoteEndpointMessageProperty.IRemoteEndpointProvider.GetAddress()
            {
                if (!this.isClosed)
                {
                    lock (this.ThisLock)
                    {
                        if (!this.isClosed)
                        {
                            return this.result.Application.Request.UserHostAddress;
                        }
                    }
                }
                return string.Empty;
            }


            [Fx.Tag.SecurityNote(Critical = "Calls getters with LinkDemands in ASP .NET objects",
                Safe = "Does not leak control or mutable/harmful data, no potential for harm")]
            [SecuritySafeCritical]
            int RemoteEndpointMessageProperty.IRemoteEndpointProvider.GetPort()
            {
                int port = 0;

                if (!this.isClosed)
                {
                    lock (this.ThisLock)
                    {
                        if (!this.isClosed)
                        {
                            string remotePort = this.result.Application.Request.ServerVariables["REMOTE_PORT"];
                            if (string.IsNullOrEmpty(remotePort) || !int.TryParse(remotePort, out port))
                            {
                                port = 0;
                            }
                        }
                    }
                }

                return port;
            }

            [Fx.Tag.SecurityNote(Critical = "Calls getters with LinkDemands in ASP .NET objects",
                Safe = "Does not leak control or mutable/harmful data, no potential for harm")]
            [SecuritySafeCritical]
            public bool TryGetAddressAndPort(out string address, out int port)
            {
                address = string.Empty;
                port = 0;

                if (!this.isClosed)
                {
                    lock (this.ThisLock)
                    {
                        if (!this.isClosed)
                        {
                            address = this.result.Application.Request.UserHostAddress;

                            IServiceProvider provider = (IServiceProvider)result.Application.Context;
                            port = GetRemotePort(provider);
                            return true;
                        }
                    }
                }
                return false;
            }

            [Fx.Tag.SecurityNote(Critical = "Asserts UnmanagedCode to get the HttpWorkerRequest.", Safe = "Only returns the remote port, doesn't leak the HttpWorkerRequest.")]
            [SecuritySafeCritical]
            [SecurityPermission(SecurityAction.Assert, UnmanagedCode = true)]
            static int GetRemotePort(IServiceProvider provider)
            {
                return ((HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest))).GetRemotePort();
            }
        }
    }
}