[英]re writing response body asp.net core custome middleware
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;
}
}
}
}
}
I have created custom middleware asp.net core to modify response body but response is blank on client side after我创建了自定义中间件 asp.net 核心来修改响应主体,但之后客户端的响应为空白
context.Response.Body = data; context.Response.Body = 数据; seems to not work any help on this is appreciated
似乎对此不起作用任何帮助表示赞赏
Try like below code it might work.试试下面的代码,它可能会起作用。 I have commented 3 lines and added few below that.
我已经评论了 3 行,并在下面添加了一些。 I was stuck in similar condition and I have got it solved with multiple answers from different references.
我被困在类似的情况下,我已经通过来自不同参考的多个答案解决了这个问题。 Like below links.
就像下面的链接。
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.