【问题标题】:Get request body after exception in middleware. .NET Core 3.1中间件异常后获取请求正文。 .NET 核心 3.1
【发布时间】:2021-08-21 08:24:35
【问题描述】:

我需要在我的ExceptionHandlingMiddleware 中获取异常后的请求正文。在异常之前我得到简单的请求正文,但在我不能之后。 部分代码来自下面ExceptionHandlingMiddleware

    try
    {
      await _next.Invoke(context);
    }
    catch (Exception exception)
    {
      RequestBody = await FormatRequest(context.Request);
    }

    private async Task<string> FormatRequest(HttpRequest request)
    {
        request.EnableBuffering();

        var body = request.Body;

        var buffer = new byte[Convert.ToInt32(request.ContentLength)];

        await request.Body.ReadAsync(buffer, 0, buffer.Length);

        var bodyAsText = Encoding.UTF8.GetString(buffer);

        return $"{request.Scheme} {request.Host}{request.Path} {request.QueryString} 
        {bodyAsText}";
    }

结果,我明白了

body

我试图通过这种方式将身体放在try

    try
    {
     RequestBody = await FormatRequest(context.Request);
     await _next.Invoke(context);
    }

它有效,我得到了正常的json 数据,但我的模型是空的,所以我的模型无效。

我试图在异常之前做request.EnableBuffering();,但它没有帮助我。

因此,如果我尝试在异常后获取正文,我将无法解析它。如果我在异常之前得到它,我在控制器中的模型无效。

登录ExceptionHandlingMiddleware出现异常后如何获取模型?

【问题讨论】:

  • 嗨@Stan,你能分享你的整个 ExceptionHandlingMiddleware 吗?尝试使用代码将流倒回到 0:request.Body.Position = 0;
  • @Rena 对不起,是你。 ;) 评论中的名称错误。帮我这个request.Body.Position = 0;请创建答案

标签: c# asp.net-core middleware


【解决方案1】:

通常Request.Body不支持倒带,所以只能读取一次。临时解决方法是在调用 EnableBuffering 后立即拉出正文,然后将流倒回到 0 并且不处理它:

request.EnableBuffering();

var body = request.Body;

var buffer = new byte[Convert.ToInt32(request.ContentLength)];

await request.Body.ReadAsync(buffer, 0, buffer.Length);

var bodyAsText = Encoding.UTF8.GetString(buffer);

request.Body.Position = 0;  //rewinding the stream to 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2022-07-08
    相关资源
    最近更新 更多