修改MVC 6的原始html输出

时间:2014-12-12 21:54:52

标签: asp.net-core asp.net-core-mvc

像webmarkupmin这样的插件使用HTTP模块从HTTPContext修改HTTP响应体:

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

如何使用ASP.NET 5中的新HTTP管道修改每个请求的原始HTTP响应主体?

1 个答案:

答案 0 :(得分:5)

我认为以下示例可以帮助您。我认为在ASP.net 5中我们必须遵循OWIN样式管道。

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