.Net Core Bad Request Log in Middleware 获取请求参数

.Net Core Bad Request Log in Middleware get request parameters

你好我有一个核心api。在 Api 中,我还想记录请求详细信息。我在下面写了代码

using InfiniteDocumentsAPI.Core.Services;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MBFSPT_OCRABBYY_InfiniteDocumentsAPI.Middlewares
{
    public class RequestLoggingMiddleware
    {
        
        private readonly RequestDelegate _next;

        public RequestLoggingMiddleware(RequestDelegate next )
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context, LoggerService log)
        {
            try
            {
                await _next(context);
            }
            finally
            {
                if (context.Response?.StatusCode == 400)
                {            
                    string requestStr = "";
                    context.Request.EnableBuffering();
                    using (var reader = new StreamReader(context.Request.Body))
                    {
                        requestStr =await reader.ReadToEndAsync();
                    }
                    context.Request.Body.Position = 0;
                    log.Trace("casa", "1", "12", 0, "dasd");
                
                }                              
            }
        }     
    }
}

上面的代码没有错误。但是在调用 await reader.ReadToEndAsync() 之后 requestStr 是空字符串。我的失踪在哪里?如何获取请求正文参数?

这是api回应

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-b9f2fb6ba6f784439cb14fad88c2819a-9a5b8bd86b38874d-00",
  "errors": {
    "$.applicationInfo.applicationId": [
      "The JSON value could not be converted to System.Int32. Path: $.applicationInfo.applicationId | LineNumber: 0 | BytePositionInLine: 1882."
    ]
  }
}

这是请求

"applicationInfo": {
        "applicationStatusLocalText": "Submitted",
        "applicationStatusCode": "08",
        "applicationNumber": "210531-0008",
        "applicationType": "Walk-in",
        "applicationId": 42434,
        "applicationPreferredCommunicationChannelTypeCode": "Email",
        "financeGroupDesc": "Installment Finance",
        "financeGroup": "IF",
        "applicantType": "Company",
        "customerSegment": "SME",
        "applicationPurposeCode": "Corporate"
      }

根据响应我只需要错误列表。从请求中我想提取一些参数,例如 applicationNumber,applicationStatusLocalText

所以在日志中我想用

调用这段代码
log.Trace("BatchNotCreated"+stringfiedResponsesErrorList, applicationId, applicationNumber, 0, `applicationStatusLocalText`);

提前致谢

像下面这样更改您的代码:

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;
    public RequestLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext context)
    {
        try
        {
            context.Request.EnableBuffering();    //add this...             
            await _next(context);
            context.Request.Body.Position = 0;    //add this...
        }
        finally
        {
            if (context.Response?.StatusCode == 400)
            {
                string applicationNumber = "";
                string requestStr = "";
                using (var reader = new StreamReader(context.Request.Body))
                {
                    requestStr = await reader.ReadToEndAsync();
                    //do your stuff....
                    var model = JObject.Parse(requestStr);
                    applicationNumber = model["applicationNumber"].ToString();
                }

                context.Request.Body.Position = 0;
            }
        }
    }
}