相关疑难解决方法(0)

如何在asp.net核心webapi控制器中读取请求体?

我正试图在OnActionExecuting方法中读取请求体,但我总是null为身体做准备.

var request = context.HttpContext.Request;
var stream = new StreamReader(request.Body);
var body = stream.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)

我试图将流位置显式设置为0,但这也不起作用.由于这是ASP.NET CORE,我认为事情没有什么不同.我可以在这里看到所有的示例,指的是旧的webapi版本.
有没有其他方法这样做?

c# asp.net-web-api asp.net-core

71
推荐指数
10
解决办法
7万
查看次数

读取 Filter 中的 Response.Body 流

我编写了在服务器方法调用后运行的过滤器,并将其内容打印到控制台。代码是用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

结果-异常:

流不可读。

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

  1. 可以读取 = false
  2. 可以寻找=假

这可以解释为什么它无法读取正文......

怎么解决?

c# asp.net asp.net-web-api asp.net-core

9
推荐指数
1
解决办法
1万
查看次数

标签 统计

asp.net-core ×2

asp.net-web-api ×2

c# ×2

asp.net ×1