问题描述
我将Asp.Net Core用作Rest Api服务.我需要访问ActionFilter中的请求和响应.实际上,我在OnActionExcecuted中找到了请求,但无法读取响应结果.
I'm using Asp.Net Core as a Rest Api Service.I need access to request and response in ActionFilter. Actually, I found the request in OnActionExcecuted but I can't read the response result.
我正在尝试按以下方式返回值:
I'm trying to return value as follow:
[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的OnExcecuted方法中,如下所示:
And in ActionFilter OnExcecuted method as follow:
_request = context.HttpContext.Request.ReadAsString().Result;
_response = context.HttpContext.Response.ReadAsString().Result; //?
我正在尝试获取ReadAsString中的响应作为扩展方法,如下所示:
I'm trying to get the response in ReadAsString as an Extension method as follow:
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;
}
但是,没有结果!
如何在OnActionExcecuted中获得响应?
How I can get the response in OnActionExcecuted?
感谢大家花时间尝试并帮助解释
Thanks, everyone for taking the time to try and help explain
推荐答案
如果您要记录json结果/查看结果,则无需读取整个响应流.只需序列化context.Result
:
If you're logging for json result/ view result , you don't need to read the whole response stream. Simply serialize the context.Result
:
public class MyFilterAttribute : ActionFilterAttribute
{
private ILogger<MyFilterAttribute> logger;
public MyFilterAttribute(ILogger<MyFilterAttribute> logger){
this.logger = logger;
}
public override void OnActionExecuted(ActionExecutedContext context)
{
var result = context.Result;
if (result is JsonResult json)
{
var x = json.Value;
var status = json.StatusCode;
this.logger.LogInformation(JsonConvert.SerializeObject(x));
}
if(result is ViewResult view){
// I think it's better to log ViewData instead of the finally rendered template string
var status = view.StatusCode;
var x = view.ViewData;
var name = view.ViewName;
this.logger.LogInformation(JsonConvert.SerializeObject(x));
}
else{
this.logger.LogInformation("...");
}
}
这篇关于阅读ActionFilterAttribute中的Asp.Net Core Response正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!