-
Notifications
You must be signed in to change notification settings - Fork 336
Expand file tree
/
Copy pathOwinClientHandler.cs
More file actions
213 lines (188 loc) · 8.11 KB
/
OwinClientHandler.cs
File metadata and controls
213 lines (188 loc) · 8.11 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
// 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;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Owin.Testing
{
/// <summary>
/// This adapts HttpRequestMessages to OWIN requests, dispatches them through the OWIN pipeline, and returns the
/// associated HttpResponseMessage.
/// </summary>
public class OwinClientHandler : HttpMessageHandler
{
private readonly Func<IDictionary<string, object>, Task> _next;
/// <summary>
/// Create a new handler.
/// </summary>
/// <param name="next">The OWIN pipeline entry point.</param>
public OwinClientHandler(Func<IDictionary<string, object>, Task> next)
{
if (next == null)
{
throw new ArgumentNullException("next");
}
_next = next;
}
/// <summary>
/// This adapts HttpRequestMessages to OWIN requests, dispatches them through the OWIN pipeline, and returns the
/// associated HttpResponseMessage.
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
var state = new RequestState(request, cancellationToken);
HttpContent requestContent = request.Content ?? new StreamContent(Stream.Null);
Stream body = await requestContent.ReadAsStreamAsync();
if (body.CanSeek)
{
// This body may have been consumed before, rewind it.
body.Seek(0, SeekOrigin.Begin);
}
state.OwinContext.Request.Body = body;
CancellationTokenRegistration registration = cancellationToken.Register(state.Abort);
// Async offload, don't let the test code block the caller.
Task offload = Task.Factory.StartNew(async () =>
{
try
{
await _next(state.Environment);
state.CompleteResponse();
}
catch (Exception ex)
{
state.Abort(ex);
}
finally
{
registration.Dispose();
state.Dispose();
}
}, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
return await state.ResponseTask.ConfigureAwait(false);
}
private class RequestState : IDisposable
{
private readonly HttpRequestMessage _request;
private Action _sendingHeaders;
private TaskCompletionSource<HttpResponseMessage> _responseTcs;
private ResponseStream _responseStream;
internal RequestState(HttpRequestMessage request, CancellationToken cancellationToken)
{
_request = request;
_responseTcs = new TaskCompletionSource<HttpResponseMessage>();
_sendingHeaders = () => { };
if (request.RequestUri.IsDefaultPort)
{
request.Headers.Host = request.RequestUri.Host;
}
else
{
request.Headers.Host = request.RequestUri.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped);
}
OwinContext = new OwinContext();
OwinContext.Set("owin.Version", "1.0");
IOwinRequest owinRequest = OwinContext.Request;
owinRequest.Protocol = "HTTP/" + request.Version.ToString(2);
owinRequest.Scheme = request.RequestUri.Scheme;
owinRequest.Method = request.Method.ToString();
owinRequest.Path = PathString.FromUriComponent(request.RequestUri);
owinRequest.PathBase = PathString.Empty;
owinRequest.QueryString = QueryString.FromUriComponent(request.RequestUri);
owinRequest.CallCancelled = cancellationToken;
owinRequest.Set<Action<Action<object>, object>>("server.OnSendingHeaders", (callback, state) =>
{
var prior = _sendingHeaders;
_sendingHeaders = () =>
{
prior();
callback(state);
};
});
foreach (var header in request.Headers)
{
owinRequest.Headers.AppendValues(header.Key, header.Value.ToArray());
}
HttpContent requestContent = request.Content;
if (requestContent != null)
{
foreach (var header in request.Content.Headers)
{
owinRequest.Headers.AppendValues(header.Key, header.Value.ToArray());
}
}
_responseStream = new ResponseStream(CompleteResponse);
OwinContext.Response.Body = _responseStream;
OwinContext.Response.StatusCode = 200;
}
public IOwinContext OwinContext { get; private set; }
public IDictionary<string, object> Environment
{
get { return OwinContext.Environment; }
}
public Task<HttpResponseMessage> ResponseTask
{
get { return _responseTcs.Task; }
}
internal void CompleteResponse()
{
if (!_responseTcs.Task.IsCompleted)
{
HttpResponseMessage response = GenerateResponse();
// Dispatch, as TrySetResult will synchronously execute the waiters callback and block our Write.
Task.Factory.StartNew(() => _responseTcs.TrySetResult(response));
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope",
Justification = "HttpResposneMessage must be returned to the caller.")]
internal HttpResponseMessage GenerateResponse()
{
_sendingHeaders();
var response = new HttpResponseMessage();
response.StatusCode = (HttpStatusCode)OwinContext.Response.StatusCode;
response.ReasonPhrase = OwinContext.Response.ReasonPhrase;
response.RequestMessage = _request;
// response.Version = owinResponse.Protocol;
response.Content = new StreamContent(_responseStream);
foreach (var header in OwinContext.Response.Headers)
{
if (!response.Headers.TryAddWithoutValidation(header.Key, header.Value))
{
bool success = response.Content.Headers.TryAddWithoutValidation(header.Key, header.Value);
Contract.Assert(success, "Bad header");
}
}
return response;
}
internal void Abort()
{
Abort(new OperationCanceledException());
}
internal void Abort(Exception exception)
{
_responseStream.Abort(exception);
_responseTcs.TrySetException(exception);
}
public void Dispose()
{
_responseStream.Dispose();
// Do not dispose the request, that will be disposed by the caller.
}
}
}
}