在 ActionFilterAttribute 中读取 Asp.Net Core Response body [英] Read Asp.Net Core Response body in ActionFilterAttribute

查看:27
本文介绍了在 ActionFilterAttribute 中读取 Asp.Net Core Response body的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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 body的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆