我正在使用 Asp.Net Core 作为 Rest Api 服务。我需要在 ActionFilter 中访问请求和响应。实际上,我在 OnActionExecuted 中找到了请求,但我无法读取响应结果。
我尝试按以下方式返回值:
[HttpGet]
[ProducesResponseType(typeof(ResponseType), (int)HttpStatusCode.OK)]
[Route("[action]")]
public async Task<IActionResult> Get(CancellationToken cancellationToken)
{
var model = await _responseServices.Get(cancellationToken);
return Ok(model);
}
在ActionFilter的OnExecuted方法中,如下所示:
_request = context.HttpContext.Request.ReadAsString().Result;
_response = context.HttpContext.Response.ReadAsString().Result; //?
我试图将以下代码作为扩展方法来获取ReadAsString的响应:
我试图将以下代码作为扩展方法来获取ReadAsString的响应:
public static async Task<string> ReadAsString(this HttpResponse response)
{
var initialBody = response.Body;
var buffer = new byte[Convert.ToInt32(response.ContentLength)];
await response.Body.ReadAsync(buffer, 0, buffer.Length);
var body = Encoding.UTF8.GetString(buffer);
response.Body = initialBody;
return body;
}
但是,没有结果!
我如何在 OnActionExecuted 中获取响应?
感谢大家抽出时间尝试帮助解释。