ecm_dev
ecm_dev

Reputation: 426

Modifying the raw html output from MVC 6

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?

Upvotes: 3

Views: 3068

Answers (1)

dotnetstep
dotnetstep

Reputation: 17485

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" });                    
    });

Upvotes: 5

Related Questions