Skip to content

Instantly share code, notes, and snippets.

@aqwert
Created April 18, 2017 22:51
Show Gist options
  • Save aqwert/492cc1631b72cec418e7a7a270a95caf to your computer and use it in GitHub Desktop.
Save aqwert/492cc1631b72cec418e7a7a270a95caf to your computer and use it in GitHub Desktop.
ASPNetCore Change response via Middleware
namespace Project
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//...
app.Use(async (context, next) =>
{
await RewriteResponse(context, next);
});
//This needs to be after Middleware
app.UseMvc(routes =>
{
routes.MapSpaFallbackRoute("spa-fallback", new { controller = "home", action = "index" });
});
}
public async Task RewriteResponse(HttpContext context, Func<Task> next)
{
using (var responseBodyStream = new MemoryStream())
{
var bodyStream = context.Response.Body;
try
{
context.Response.Body = responseBodyStream;
await next();
responseBodyStream.Seek(0, SeekOrigin.Begin);
var responseBody = new StreamReader(responseBodyStream).ReadToEnd();
//Modify the response in some way (Example)
responseBody = responseBody.Replace(@"\n", @"<br/>");
using (var newStream = new MemoryStream())
{
var sw = new StreamWriter(newStream);
sw.Write(responseBody);
sw.Flush();
newStream.Seek(0, SeekOrigin.Begin);
await newStream.CopyToAsync(bodyStream);
}
}
finally
{
context.Response.Body = bodyStream;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment