gpt4 book ai didi

c# - 在 Filter 中读取 Response.Body 流

转载 作者:太空宇宙 更新时间:2023-11-03 12:10:03 25 4
gpt4 key购买 nike

我编写了在服务器方法调用后运行的过滤器,并将其内容打印到控制台。代码使用 ASP.NET core v2.1 编写:

public class MyCustomFilter : ActionFilterAttribute
{
public override void OnResultExecuted(ResultExecutedContext context)
{

// ERROR on the next line!
using (StreamReader sr = new StreamReader(context.HttpContext.Response.Body))
{
Console.WriteLine(sr.ReadToEnd());
}

base.OnResultExecuted(context);
}
}

结果 - 异常:

Stream was not readable.

进一步调查使我发现流 (context.HttpContext.Response) 具有这些值:

  1. CanRead = false
  2. CanSeek = false

这可以解释为什么它不能读取正文...

如何解决?

最佳答案

不确定为什么需要这样做。 context.ResultIActionResult 的一个实例,你可以随意操作它。如果您确实想阅读 Response.Body ,可以做一些 hacky 的事情。

由于默认的Response.Body不是一个可读的Stream,为了让正文可读,我们需要劫持响应,即替换Body 与我们自己的 Stream 实例:

  1. 我们可以在 Action 执行之前动态创建一个全新的内存流,并劫持默认的Response.Body 流。
  2. 执行操作时,使用 StreamReader 读取流,做一些工作,然后设置 Response.Body=your new stream

用纯内存流劫持 Response.Body 是安全的,因为 Body 的类型是纯 Stream

public class MyCustomFilter : ActionFilterAttribute
{
private MemoryStream responseBody ;

public override void OnActionExecuting(ActionExecutingContext context){
this.responseBody=new MemoryStream();
// hijack the real stream with our own memory stream
context.HttpContext.Response.Body = responseBody;
}

public override void OnResultExecuted(ResultExecutedContext context)
{

responseBody.Seek(0, SeekOrigin.Begin);

// read our own memory stream
using (StreamReader sr = new StreamReader(responseBody))
{
var actionResult= sr.ReadToEnd();
Console.WriteLine(actionResult);
// create new stream and assign it to body
// context.HttpContext.Response.Body = ;
}

// no ERROR on the next line!

base.OnResultExecuted(context);
}
}

出于测试目的,我创建了一个操作方法:

[MyCustomFilter]
public IActionResult Index()
{
return Ok("it wooooooooorks");
}

enter image description here

关于c# - 在 Filter 中读取 Response.Body 流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52849296/

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