如何使用.NET Core中间件将HTML插入Response主体

时间:2019-02-14 18:58:50

标签: asp.net-mvc http asp.net-core html-agility-pack asp.net-core-middleware

我一直在尝试整理一些中间件,这些中间件将使我能够评估请求的处理时间。 This的示例为我提供了一个很好的起点,但是我遇到了麻烦。

在下面的代码中,我能够测量处理时间并将其插入到div中(使用HTML Agility Pack)。但是,页面的原始内容会重复。我认为我在context.Response.Body中的UpdateHtml()属性上做错了,但无法弄清楚它是什么。 (我在代码中做了一些注释。)如果您发现任何看起来不正确的内容,请告诉我吗?

谢谢。

public class ResponseMeasurementMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        var watch = new Stopwatch();
        watch.Start();
        context.Response.OnStarting(async () =>
        {
            var responseTime = watch.ElapsedMilliseconds;
            var newContent = string.Empty;
            var existingBody = context.Response.Body;
            string updatedHtml = await UpdateHtml(responseTime, context);

            await context.Response.WriteAsync(updatedHtml);
        });

        await _next.Invoke(context);
    }

    private async Task<string> UpdateHtml(long responseTime, HttpContext context)
    {
        var newContent = string.Empty;
        var existingBody = context.Response.Body;
        string updatedHtml = "";
        //I think I'm doing something incorrectly in this using...
        using (var newBody = new MemoryStream())
        {
            context.Response.Body = newBody;

            await _next(context);

            context.Response.Body = existingBody;
            newBody.Position = 0;

            newContent = await new StreamReader(newBody).ReadToEndAsync();
            updatedHtml = CreateDataNode(newContent, responseTime);
        }

        return updatedHtml;
    }

    private string CreateDataNode(string originalHtml, long responseTime)
    {
        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(originalHtml);
        HtmlNode testNode = HtmlNode.CreateNode($"<div><h2>Inserted using Html Agility Pack: Response Time: {responseTime.ToString()} ms.</h2><div>");
        var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
        htmlBody.InsertBefore(testNode, htmlBody.FirstChild);

        string rawHtml = htmlDoc.DocumentNode.OuterHtml; //using this results in a page that displays my inserted HTML correctly, but duplicates the original page content.
        //rawHtml = "some text"; uncommenting this results in a page with the correct format: this text, followed by the original contents of the page

        return rawHtml;
    }
}

1 个答案:

答案 0 :(得分:1)

对于重复的html,它是由await _next(context);中的UpdateHtml引起的,它将调用其余的中间件(如MVC)来处理请求和响应。

在没有await _next(context);的情况下,您不应在context.Response.OnStarting中修改响应正文。

要解决此问题,建议您将ResponseMeasurementMiddleware放置为第一个中间件,然后像

那样计算时间
public class ResponseMeasurementMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        var originalBody = context.Response.Body;
        var newBody = new MemoryStream();
        context.Response.Body = newBody;

        var watch = new Stopwatch();
        long responseTime = 0;
        watch.Start();
        await _next(context);
        //// read the new body
        // read the new body
        responseTime = watch.ElapsedMilliseconds;
        newBody.Position = 0;
        var newContent = await new StreamReader(newBody).ReadToEndAsync();
        // calculate the updated html
        var updatedHtml = CreateDataNode(newContent, responseTime);
        // set the body = updated html
        var updatedStream = GenerateStreamFromString(updatedHtml);
        await updatedStream.CopyToAsync(originalBody);
        context.Response.Body = originalBody;

    }
    public static Stream GenerateStreamFromString(string s)
    {
        var stream = new MemoryStream();
        var writer = new StreamWriter(stream);
        writer.Write(s);
        writer.Flush();
        stream.Position = 0;
        return stream;
    }
    private string CreateDataNode(string originalHtml, long responseTime)
    {
        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(originalHtml);
        HtmlNode testNode = HtmlNode.CreateNode($"<div><h2>Inserted using Html Agility Pack: Response Time: {responseTime.ToString()} ms.</h2><div>");
        var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");
        htmlBody.InsertBefore(testNode, htmlBody.FirstChild);

        string rawHtml = htmlDoc.DocumentNode.OuterHtml; //using this results in a page that displays my inserted HTML correctly, but duplicates the original page content.
                                                         //rawHtml = "some text"; uncommenting this results in a page with the correct format: this text, followed by the original contents of the page

        return rawHtml;
    }
}

并像

一样注册ResponseMeasurementMiddleware
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMiddleware<ResponseMeasurementMiddleware>();
    //rest middlwares
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

通过这种方式app.UseMiddleware<ResponseMeasurementMiddleware>();,操作将是发送响应之前的最后一次操作,然后处理时间将适合于处理时间。