-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseProxyMiddleware.cs
188 lines (163 loc) · 7.07 KB
/
ReverseProxyMiddleware.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace iisbridge {
public class ReverseProxyMiddleware
{
private const int INITIAL_REQUEST_TIMEOUT = 20000;
private static readonly HttpClient httpClient = new HttpClient(new HttpClientHandler() { UseCookies = false });
private readonly RequestDelegate nextMiddleware;
private readonly ReverseProxyOptions options;
private readonly ExecutableHandler exeHandler;
public ReverseProxyMiddleware(RequestDelegate nextMiddleware, ReverseProxyOptions options)
{
this.nextMiddleware = nextMiddleware;
this.options = options;
this.exeHandler = options.ExecutableHandler;
}
public async Task Invoke(HttpContext context)
{
// Ensure Web-App is started
if (!exeHandler.Started)
{
exeHandler.Start();
}
if (!exeHandler.StartFailed)
{
// Create Source
var targetUri = BuildTargetUri(context.Request);
if (targetUri != null)
{
// Create Request for target & send it
var targetRequestMessage = CreateTargetMessage(context, targetUri);
Console.WriteLine(targetRequestMessage.Headers.ToString());
using (var responseMessage = await GetTargetResponse(context, targetRequestMessage))
{
context.Response.StatusCode = (int)responseMessage.StatusCode;
CopyFromTargetResponseHeaders(context, responseMessage);
await responseMessage.Content.CopyToAsync(context.Response.Body);
}
return;
}
}
else
{
throw new Exception("Start of WebApp Executable failed!");
}
await nextMiddleware(context);
}
public async Task<HttpResponseMessage> GetTargetResponse(HttpContext context, HttpRequestMessage targetRequestMessage) {
try
{
var response = await httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted);
return response;
}
catch (HttpRequestException ex)
{
// If initial request timeout is not reached yet
if (exeHandler.StartedTime.HasValue && exeHandler.StartedTime.Value > DateTime.Now.AddMilliseconds(-INITIAL_REQUEST_TIMEOUT))
{
await Task.Delay(1000);
return await GetTargetResponse(context, Clone(targetRequestMessage));
}
else
{
throw ex;
}
}
}
private HttpRequestMessage CreateTargetMessage(HttpContext context, Uri targetUri)
{
var requestMessage = new HttpRequestMessage();
CopyFromOriginalRequestContentAndHeaders(context, requestMessage);
requestMessage.RequestUri = targetUri;
requestMessage.Headers.Host = targetUri.Host;
requestMessage.Method = GetMethod(context.Request.Method);
// Add user authenticated by Windows Auth
requestMessage.Headers.Remove("x-auth-user");
requestMessage.Headers.Add("x-auth-user", context.User.Identity.Name ?? "Unknown");
return requestMessage;
}
private void CopyFromOriginalRequestContentAndHeaders(HttpContext context, HttpRequestMessage requestMessage)
{
var requestMethod = context.Request.Method;
if (!HttpMethods.IsGet(requestMethod) &&
!HttpMethods.IsHead(requestMethod) &&
!HttpMethods.IsDelete(requestMethod) &&
!HttpMethods.IsTrace(requestMethod))
{
var streamContent = new StreamContent(context.Request.Body);
requestMessage.Content = streamContent;
}
foreach (var header in context.Request.Headers)
{
requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
}
foreach (var header in context.Request.Headers)
{
requestMessage?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
}
}
private void CopyFromTargetResponseHeaders(HttpContext context, HttpResponseMessage responseMessage)
{
foreach (var header in responseMessage.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
foreach (var header in responseMessage.Content.Headers)
{
context.Response.Headers[header.Key] = header.Value.ToArray();
}
context.Response.Headers.Remove("transfer-encoding");
}
private static HttpMethod GetMethod(string method)
{
if (HttpMethods.IsDelete(method)) return HttpMethod.Delete;
if (HttpMethods.IsGet(method)) return HttpMethod.Get;
if (HttpMethods.IsHead(method)) return HttpMethod.Head;
if (HttpMethods.IsOptions(method)) return HttpMethod.Options;
if (HttpMethods.IsPost(method)) return HttpMethod.Post;
if (HttpMethods.IsPut(method)) return HttpMethod.Put;
if (HttpMethods.IsTrace(method)) return HttpMethod.Trace;
return new HttpMethod(method);
}
private Uri BuildTargetUri(HttpRequest request)
{
string requestPath = request.Path.ToString();
string queryString = request.QueryString.ToString();
return new Uri(options.BaseUrl + requestPath + queryString);
}
public HttpRequestMessage Clone(HttpRequestMessage req)
{
HttpRequestMessage clone = new HttpRequestMessage(req.Method, req.RequestUri);
clone.Content = req.Content;
clone.Version = req.Version;
foreach (KeyValuePair<string, object> prop in req.Properties)
{
clone.Properties.Add(prop);
}
foreach (KeyValuePair<string, IEnumerable<string>> header in req.Headers)
{
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
return clone;
}
}
public static class ReverseProxyMiddlewareExtensions
{
public static IApplicationBuilder UseReverseProxy(this IApplicationBuilder app, ReverseProxyOptions options)
{
return app.UseMiddleware<ReverseProxyMiddleware>(options);
}
}
public class ReverseProxyOptions
{
public string BaseUrl { get; set; }
public ExecutableHandler ExecutableHandler { get; set;}
}
}