3

Plugins like webmarkupmin modify the HTTP response body from the HTTPContext using an HTTP module like this:

protected override void ProcessContent(HttpContext context)
    {
        HttpRequest request = context.Request;
        HttpResponse response = context.Response;
        Encoding encoding = response.ContentEncoding;
        string contentType = response.ContentType;

        if (request.HttpMethod == "GET" && response.StatusCode == 200
            && contentType == ContentType.Html
            && context.CurrentHandler != null)
        {
            var htmlMinifier = WebMarkupMinContext.Current.Markup.CreateHtmlMinifierInstance();
            response.Filter = new HtmlMinificationFilterStream(response.Filter, htmlMinifier,
                request.RawUrl, encoding);

            if (WebMarkupMinContext.Current.IsCopyrightHttpHeadersEnabled())
            {
                CopyrightHelper.AddHtmlMinificationPoweredByHttpHeader(response);
            }
        }
    }

How would you modify the raw HTTP response body per request using the new HTTP Pipeline in ASP.NET 5?

2
  • Should have added this: by modify I mean read out the response body as a string so that it can be modified, then set that new content as the response body to be sent. Commented Dec 13, 2014 at 0:27
  • Strange, it appears as though the Response.Body.CanRead property is not settable... Commented Dec 13, 2014 at 0:43

1 Answer 1

5

I think that following example will help you on that. I think in ASP.net 5 we have to follow OWIN style pipeline.

Here is some sample code from Startup.cs

 app.Use(async (context, next) =>
    {
        // Wrap and buffer response body.
        // Expect built in support for this at some point. The current code is prerelease
        var buffer = new MemoryStream();
        var stream = context.Response.Body;
        context.Response.Body = buffer;

        await next();

        if (context.Response.StatusCode == 200 && 
            context.Response.ContentType.Equals("application/html", StringComparison.OrdinalIgnoreCase))
        {
            buffer.Seek(0, SeekOrigin.Begin);
            var reader = new StreamReader(buffer);
            string responseBody = await reader.ReadToEndAsync();                    
            MemoryStream msNew = new MemoryStream();
            using (StreamWriter wr = new StreamWriter(msNew))
            {
                 wr.WriteLine("This is my new content");
                 wr.Flush();
                 msNew.Seek(0, SeekOrigin.Begin);
                 await msNew.CopyToAsync(stream);
            }
        }
    });


    // Add MVC to the request pipeline.
    app.UseMvc(routes =>
    {
         routes.MapRoute(
         name: "default",
         template: "{controller}/{action}/{id?}",
         defaults: new { controller = "Home", action = "Index" });                    
    });
Sign up to request clarification or add additional context in comments.

6 Comments

This is very close to what I need to do - with that I can append text to the bottom of the page but I need to be able to read out the response body as a string and modify that. I've tried using this:
var encoding = context.Response.Headers["Content-Encoding"]; using (StreamReader reader = new StreamReader(context.Response.Body)) { string text = reader.ReadToEnd(); }
But I get this exception: ArgumentException: Stream was not readable
Check update I have resolved the issue of stream not readable.
@Yishai Galatzer: Actually I have made sample for specific path and you have added contenttype html so don'y you think it will do for all request ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.