我需要將我的請求和回應 JSON 保存在資料庫中,到目前為止我沒有找到任何代碼來這樣做。
在較舊的 .net 核心版本中,我使用以下代碼讀取正文:
context.Request.EnableRewind();
但似乎這段代碼在 .Net 6 中不起作用,或者我不知道使用它的技巧,這是我的最后一個代碼,它能夠讀取回應但請求始終為空。
public class APILogFilter : IActionFilter
{
public async void OnActionExecuted(ActionExecutedContext context)
{
string RequestBody = "";
context.HttpContext.Request.EnableBuffering();
using (StreamReader reader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8, true, 1024, true))
{
RequestBody = await reader.ReadToEndAsync();
};
string ResultBody = "";
if (context.Result is ObjectResult)
{
var objResult = (ObjectResult)context.Result;
ResultBody = HelperConvert.GetJSONSerialize(objResult.Value);
}
//Save request and response in database
}
public void OnActionExecuting(ActionExecutingContext context)
{
}
}
我希望有人可以幫助我。
uj5u.com熱心網友回復:
我可以提供您使用Middleware代替過濾器。
這個中間件在 .NET 6 上運行良好。
public class BodyLoggerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<BodyLoggerMiddleware> _logger;
public BodyLoggerMiddleware(RequestDelegate next, ILogger<BodyLoggerMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
string requestBody;
context.Request.EnableBuffering();
using (StreamReader reader = new StreamReader(context.Request.Body, Encoding.UTF8, true, 1024, true))
{
requestBody = await reader.ReadToEndAsync();
}
_logger.LogInformation("Request: {Request}", requestBody);
}
finally
{
context.Request.Body.Position = 0;
}
Stream originalBody = context.Response.Body;
try
{
using (var memStream = new MemoryStream())
{
context.Response.Body = memStream;
await _next(context);
memStream.Position = 0;
string responseBody = new StreamReader(memStream).ReadToEnd();
_logger.LogInformation("Response: {Response}", responseBody);
memStream.Position = 0;
await memStream.CopyToAsync(originalBody);
}
}
finally
{
context.Response.Body = originalBody;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/392603.html
