gpt4 book ai didi

c# - 重新编写响应体 asp.net core 自定义中间件

转载 作者:行者123 更新时间:2023-12-03 19:09:26 25 4
gpt4 key购买 nike

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 core 来修改响应正文,但在客户端之后响应为空白
context.Response.Body = 数据;
似乎不起作用
对此的任何帮助表示赞赏

最佳答案

尝试像下面的代码它可能会工作。我已经评论了 3 行,并在下面添加了一些。我陷入了类似的情况,我已经通过来自不同引用文献的多个答案解决了这个问题。像下面的链接。

  • modify middleware response
  • 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;
    }
    }
    }

    关于c# - 重新编写响应体 asp.net core 自定义中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62588709/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com