Created
December 15, 2019 19:45
-
-
Save davidfowl/e81fbb63e63dce4918f86cb44378b227 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.AspNetCore.WebUtilities; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Hosting; | |
namespace WebApplication404 | |
{ | |
public class Startup | |
{ | |
public Startup(IConfiguration configuration) | |
{ | |
Configuration = configuration; | |
} | |
public IConfiguration Configuration { get; } | |
// This method gets called by the runtime. Use this method to add services to the container. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddControllers(o => | |
{ | |
o.SuppressOutputFormatterBuffering = true; | |
}) | |
.AddNewtonsoftJson(); | |
} | |
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
if (env.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
} | |
app.UseHttpsRedirection(); | |
app.UseRouting(); | |
app.Use(async (context, next) => | |
{ | |
var endpoint = context.GetEndpoint(); | |
var bufferMetadata = endpoint?.Metadata.GetMetadata<OutputBufferAttribute>(); | |
if (bufferMetadata != null) | |
{ | |
var previous = context.Response.Body; | |
try | |
{ | |
// <= 0 means disable buffering, the FileBufferingWriteStream splits up data into 1K chunks | |
// and it'll buffer in memory | |
var bufferSize = bufferMetadata.Size <= 0 ? int.MaxValue : bufferMetadata.Size; | |
await using var bufferingStream = new FileBufferingWriteStream(bufferSize); | |
context.Response.Body = bufferingStream; | |
await next(); | |
context.Response.ContentLength = bufferingStream.Length; | |
await bufferingStream.DrainBufferAsync(previous); | |
} | |
finally | |
{ | |
context.Response.Body = previous; | |
} | |
} | |
}); | |
app.UseAuthorization(); | |
app.UseEndpoints(endpoints => | |
{ | |
endpoints.MapControllers(); | |
}); | |
} | |
} | |
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)] | |
public sealed class OutputBufferAttribute : Attribute | |
{ | |
public int Size { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment