重写响应主体asp.net核心定制中间件

时间:2020-06-26 05:43:51

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

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace DemoReact
{
    public class Middlewarecustom
    {

        private readonly RequestDelegate _next;

        public Middlewarecustom(RequestDelegate next)
        {
            _next = next;
        }
        public async Task Invoke(HttpContext context) {
            using (var buffer = new MemoryStream()) {
                var stream = context.Response.Body;
                context.Response.Body = buffer;
                await _next.Invoke(context);
                buffer.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(buffer);
                using (var bufferReader = new StreamReader(buffer)) { 
                string body = await bufferReader.ReadToEndAsync();
                    WeatherForecast wf = new WeatherForecast();
                    wf.Date = DateTime.Now;
                    wf.Summary = "demo";
                    wf.TemperatureC = 31;
                    var jsonString = JsonConvert.SerializeObject(wf);
                    byte[] bytess = Encoding.ASCII.GetBytes(jsonString);
                    var data = new MemoryStream(bytess);
                    context.Response.Body = data;
                }
            }
        }
    }
}

我已经创建了自定义中间件asp.net核心来修改响应正文,但之后客户端的响应为空白
context.Response.Body =数据; 似乎不起作用 对此有任何帮助,谢谢

1 个答案:

答案 0 :(得分:1)

尝试像下面的代码可能会起作用。我评论了3行,并在其下添加了几行。我被困在类似的状况中,并通过来自不同参考文献的多个答案解决了它。就像下面的链接。

  1. modify middleware response
  2. Getting empty response on asp.net core middleware on exception

public async Task Invoke(HttpContext context) {
    using (var buffer = new MemoryStream()) {
        var stream = context.Response.Body;
        context.Response.Body = buffer;
        await _next.Invoke(context);
        buffer.Seek(0, SeekOrigin.Begin);
        var reader = new StreamReader(buffer);
        using (var bufferReader = new StreamReader(buffer)) { 
        string body = await bufferReader.ReadToEndAsync();
            WeatherForecast wf = new WeatherForecast();
            wf.Date = DateTime.Now;
            wf.Summary = "demo";
            wf.TemperatureC = 31;
            var jsonString = JsonConvert.SerializeObject(wf);
            
            // Commented below lines.
            // byte[] bytess = Encoding.ASCII.GetBytes(jsonString);
            // var data = new MemoryStream(bytess);
            // context.Response.Body = data;
            
            // Added new code
            await context.Response.WriteAsync(jsonString);
            context.Response.Body.Seek(0, SeekOrigin.Begin);
            context.Response.Body.CopyTo(stream);
            context.Response.Body = stream;
        }
    }
}