Setting a Content-Length Header in an ASP.NET 5 Response

TL DR I have an ASP.NET 5 (MVC 6) application and just trying to set the Content-Length HTTP header to avoid a response.

To my surprise, it happens that this is a rather difficult task to perform in ASP.NET 5. Everything works on Kestrel, which from ASP.NET 5 Beta7 supports automatic recording of response responses if the content length is not specified for the response.

There is a similar question here , but the difference is that the OP just wants to calculate the size of the response, while I need to make sure the Content-Length header is sent in the response. Tried a lot of things so far, and the only thing that works is to write your own middleware:

public class WebApiMiddleware {
    RequestDelegate _next;

    public WebApiMiddleware(RequestDelegate next) {
        _next = next;
    }

    public async Task Invoke(HttpContext context) {
         using (var buffer = new MemoryStream()) {
            var response = context.Response;

            var bodyStream = response.Body;
            response.Body = buffer;

            await _next(context);

            response.Headers.Add("Content-Length", new[] { buffer.Length.ToString()});
            buffer.Position = 0;
            await buffer.CopyToAsync(bodyStream);
        }
     }
}

, . , context.Response.Body , , Microsoft , , , re, , , , Content-Length , - , .

!

p.s. , chunking - HTTP/1.1, , , HTTP/1.0.

+4
1

, , .

, context.Response.Body , .

, : https://github.com/aspnet/BasicMiddleware/blob/dev/src/Microsoft.AspNet.Buffering/ResponseBufferingMiddleware.cs, , , , IHttpBufferingFeature to .

bufferStream.CanSeek , , .

: middlware.

+3

Source: https://habr.com/ru/post/1617978/


All Articles