將響應流替換爲MemoryStream
以防止發送。響應被修改後返回原始流:
public class EditResponseMiddleware
{
private readonly RequestDelegate _next;
public EditResponseMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var originBody = context.Response.Body;
var newBody = new MemoryStream();
context.Response.Body = newBody;
await _next(context);
newBody.Seek(0, SeekOrigin.Begin);
string json = new StreamReader(newBody).ReadToEnd();
context.Response.Body = originBody;
await context.Response.WriteAsync(modifiedJson);
}
}
這是一種解決方法,它可能會導致性能問題。我希望在這裏看到更好的解決方案。
This Works,thanks!我發現在某些情況下,將回調附加到'context.Response.OnStarting()'也可以,但在修改響應時不起作用。另外我不喜歡使用'OnStarting()',因爲它打破了迭代中間件工作流程。 – Matthias