diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2022-05-05 21:56:54 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2022-05-05 21:56:54 -0500 |
| commit | 15b611ccd5cc3350743e1bae23def84938abe451 (patch) | |
| tree | c764cb5044a3f145819e1256d5a0557aa188dc45 /src | |
| parent | 7e9be73142ca1ddb3f5c7523c81367e6db55a895 (diff) | |
| download | slskd-15b611ccd5cc3350743e1bae23def84938abe451.tar.gz | |
refactor to work in production
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs | 25 |
1 files changed, 22 insertions, 3 deletions
diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs index ba45c20b..41ceef51 100644 --- a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs +++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs @@ -18,8 +18,8 @@ namespace slskd { using System; + using System.IO; using System.Linq; - using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; @@ -81,14 +81,33 @@ namespace slskd if (!isApiRoute && isGET && isInjectableType) { - context.Request.EnableBuffering(); + var originalStream = context.Response.Body; + + // swap the response body out with a memory stream so we can manipulate it later + // the downstream middleware will write the response to it + var stream = new MemoryStream(); + context.Response.Body = stream; await Next.Invoke(context); if (context.Response.StatusCode == 200) { - await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(HTML)); + // something downstream responded with a 200, meaning there's data in the body + // we need to read it, so we can reset then play it back with the appended HTML + context.Response.Body.Seek(0, SeekOrigin.Begin); + var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); + + context.Response.Clear(); + await context.Response.WriteAsync(body + HTML); } + + // rewind the stream we injected to the beginning, then replay the data to the + // original stream + stream.Seek(0, SeekOrigin.Begin); + await stream.CopyToAsync(originalStream); + + // swap the original stream back in + context.Response.Body = originalStream; } else { |
