This repository was archived by the owner on Jan 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathNancyHandler.cs
171 lines (139 loc) · 5.91 KB
/
NancyHandler.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
namespace Nancy.Hosting.Aspnet
{
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Web;
using Nancy.Extensions;
using Nancy.IO;
/// <summary>
/// Bridges the communication between Nancy and ASP.NET based hosting.
/// </summary>
public class NancyHandler
{
private readonly INancyEngine engine;
/// <summary>
/// Initializes a new instance of the <see cref="NancyHandler"/> type for the specified <paramref name="engine"/>.
/// </summary>
/// <param name="engine">An <see cref="INancyEngine"/> instance, that should be used by the handler.</param>
public NancyHandler(INancyEngine engine)
{
this.engine = engine;
}
/// <summary>
/// Processes the ASP.NET request with Nancy.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContextBase"/> of the request.</param>
public async Task ProcessRequest(HttpContextBase httpContext)
{
var request = CreateNancyRequest(httpContext);
using(var nancyContext = await this.engine.HandleRequest(request).ConfigureAwait(false))
{
await SetNancyResponseToHttpResponse(httpContext, nancyContext.Response);
}
}
private static Request CreateNancyRequest(HttpContextBase context)
{
var incomingHeaders = context.Request.Headers.ToDictionary();
var expectedRequestLength =
GetExpectedRequestLength(incomingHeaders);
var basePath = context.Request.ApplicationPath.TrimEnd('/');
var path = context.Request.Url.AbsolutePath.Substring(basePath.Length);
path = string.IsNullOrWhiteSpace(path) ? "/" : path;
var nancyUrl = new Url
{
Scheme = context.Request.Url.Scheme,
HostName = context.Request.Url.Host,
Port = context.Request.Url.Port,
BasePath = basePath,
Path = path,
Query = context.Request.Url.Query,
};
byte[] certificate = null;
if (context.Request.ClientCertificate != null &&
context.Request.ClientCertificate.IsPresent &&
context.Request.ClientCertificate.Certificate.Length != 0)
{
certificate = context.Request.ClientCertificate.Certificate;
}
RequestStream body = null;
if (expectedRequestLength != 0)
{
body = RequestStream.FromStream(context.Request.InputStream, expectedRequestLength, StaticConfiguration.DisableRequestStreamSwitching ?? true);
}
var protocolVersion = context.Request.ServerVariables["HTTP_VERSION"];
return new Request(context.Request.HttpMethod.ToUpperInvariant(),
nancyUrl,
body,
incomingHeaders,
context.Request.UserHostAddress,
new X509Certificate2(certificate),
protocolVersion);
}
private static long GetExpectedRequestLength(IDictionary<string, IEnumerable<string>> incomingHeaders)
{
if (incomingHeaders == null)
{
return 0;
}
if (!incomingHeaders.ContainsKey("Content-Length"))
{
return 0;
}
var headerValue =
incomingHeaders["Content-Length"].SingleOrDefault();
if (headerValue == null)
{
return 0;
}
long contentLength;
if (!long.TryParse(headerValue, NumberStyles.Any, CultureInfo.InvariantCulture, out contentLength))
{
return 0;
}
return contentLength;
}
public static Task SetNancyResponseToHttpResponse(HttpContextBase context, Response response)
{
SetHttpResponseHeaders(context, response);
if (response.ContentType != null)
{
context.Response.ContentType = response.ContentType;
}
if (IsOutputBufferDisabled())
{
context.Response.BufferOutput = false;
}
context.Response.StatusCode = (int) response.StatusCode;
if (response.ReasonPhrase != null)
{
context.Response.StatusDescription = response.ReasonPhrase;
}
return response.Contents.Body.Invoke(new NancyResponseStream(context.Response));
}
private static bool IsOutputBufferDisabled()
{
var configurationSection =
ConfigurationManager.GetSection("nancyFx") as NancyFxSection;
if (configurationSection == null || configurationSection.DisableOutputBuffer == null)
{
return false;
}
return configurationSection.DisableOutputBuffer.Value;
}
private static void SetHttpResponseHeaders(HttpContextBase context, Response response)
{
foreach (var header in response.Headers.ToDictionary(x => x.Key, x => x.Value))
{
context.Response.AddHeader(header.Key, header.Value);
}
foreach(var cookie in response.Cookies.ToArray())
{
context.Response.AddHeader("Set-Cookie", cookie.ToString());
}
}
}
}