【问题标题】:Read Asp.Net Core Response body in ActionFilterAttribute在 ActionFilterAttribute 中读取 Asp.Net Core Response 正文
【发布时间】:2019-05-06 16:19:03
【问题描述】:

我使用 Asp.Net Core 作为 Rest Api 服务。 我需要访问 ActionFilter 中的请求和响应。实际上,我在 OnActionExcecuted 中找到了请求,但我无法读取响应结果。

我正在尝试返回值如下:

[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方法如下:

_request = context.HttpContext.Request.ReadAsString().Result;
_response = context.HttpContext.Response.ReadAsString().Result; //?

我正在尝试将 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;
 }

但是,没有结果!

如何在 OnActionExcecuted 中获得响应?

感谢大家抽出宝贵时间尝试帮助解释

【问题讨论】:

  • 谢谢,我尝试了很多方法,但所有主题都没有响应。
  • 为什么要阅读响应?虽然可以通过阅读回复来实现,但如果您告诉我们您的意图,也许会有更好的方法来实现您的目标。
  • 我需要知道哪些数据提供给客户端并将所有结果记录为 JSON @itminus

标签: asp.net asp.net-mvc asp.net-core .net-core


【解决方案1】:

如果您正在记录 json result/view result ,则无需阅读整个响应流。只需序列化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("...");
        }
    }

【讨论】:

  • 这个答案明显比我见过的其他常见解决方案更有效(无论如何都是代码),这些解决方案似乎普遍建议替换和跟踪Response.Body 的内存流!谢谢!
【解决方案2】:

对于 ASP.NET Core 过滤器管道中记录整个请求和响应,您可以使用Result filter attribute

    public class LogRequestResponseAttribute : TypeFilterAttribute
    {
        public LogRequestResponseAttribute() : base(typeof(LogRequestResponseImplementation)) { }

        private class LogRequestResponseImplementation : IAsyncResultFilter
        {
            public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
            {
                var requestHeadersText = CommonLoggingTools.SerializeHeaders(context.HttpContext.Request.Headers);
                Log.Information("requestHeaders: " + requestHeadersText);

                var requestBodyText = await CommonLoggingTools.FormatRequestBody(context.HttpContext.Request);
                Log.Information("requestBody: " + requestBodyText);

                await next();

                var responseHeadersText = CommonLoggingTools.SerializeHeaders(context.HttpContext.Response.Headers);
                Log.Information("responseHeaders: " + responseHeadersText);

                var responseBodyText = await CommonLoggingTools.FormatResponseBody(context.HttpContext.Response);
                Log.Information("responseBody: " + responseBodyText);
            }
        }
    }

在 Startup.cs 添加

    app.UseMiddleware<ResponseRewindMiddleware>();

    services.AddScoped<LogRequestResponseAttribute>();

在某处添加静态类

    public static class CommonLoggingTools
    {
        public static async Task<string> FormatRequestBody(HttpRequest request)
        {
            //This line allows us to set the reader for the request back at the beginning of its stream.
            request.EnableRewind();

            //We now need to read the request stream.  First, we create a new byte[] with the same length as the request stream...
            var buffer = new byte[Convert.ToInt32(request.ContentLength)];

            //...Then we copy the entire request stream into the new buffer.
            await request.Body.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);

            //We convert the byte[] into a string using UTF8 encoding...
            var bodyAsText = Encoding.UTF8.GetString(buffer);

            //..and finally, assign the read body back to the request body, which is allowed because of EnableRewind()
            request.Body.Position = 0;

            return $"{request.Scheme} {request.Host}{request.Path} {request.QueryString} {bodyAsText}";
        }

        public static async Task<string> FormatResponseBody(HttpResponse response)
        {
            //We need to read the response stream from the beginning...
            response.Body.Seek(0, SeekOrigin.Begin);

            //...and copy it into a string
            string text = await new StreamReader(response.Body).ReadToEndAsync();

            //We need to reset the reader for the response so that the client can read it.
            response.Body.Seek(0, SeekOrigin.Begin);

            response.Body.Position = 0;

            //Return the string for the response, including the status code (e.g. 200, 404, 401, etc.)
            return $"{response.StatusCode}: {text}";
        }

        public static string SerializeHeaders(IHeaderDictionary headers)
        {
            var dict = new Dictionary<string, string>();

            foreach (var item in headers.ToList())
            {
                //if (item.Value != null)
                //{
                var header = string.Empty;
                foreach (var value in item.Value)
                {
                    header += value + " ";
                }

                // Trim the trailing space and add item to the dictionary
                header = header.TrimEnd(" ".ToCharArray());
                dict.Add(item.Key, header);
                //}
            }

            return JsonConvert.SerializeObject(dict, Formatting.Indented);
        }
    }

    public class ResponseRewindMiddleware {
        private readonly RequestDelegate next;

        public ResponseRewindMiddleware(RequestDelegate next) {
            this.next = next;
        }

        public async Task Invoke(HttpContext context) {

            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();

                    memStream.Position = 0;
                    await memStream.CopyToAsync(originalBody);
                }

            } finally {
                context.Response.Body = originalBody;
            }

        } 

【讨论】:

    【解决方案3】:

    我知道已经有了答案,但我还想补充一点,问题是 MVC 管道在运行 Response.Body 时没有填充 Response.Body,因此您无法访问它。 Response.Body 由 MVC middleware 填充。

    如果您想阅读Response.Body,那么您需要创建自己的自定义中间件,以便在填充 Response 对象时拦截调用。有许多网站可以向您展示如何做到这一点。一个例子是here。

    如另一个答案中所述,如果您想在 ActionFilter 中进行操作,您可以使用 context.Result 访问信息。

    【讨论】:

      【解决方案4】:

      你也可以...

      string response = "Hello";
      if (result is ObjectResult objectResult)
              {
                  var status = objectResult.StatusCode;
                  var value = objectResult.Value;
                  var stringResult = objectResult.ToString();
                  responce = (JsonConvert.SerializeObject(value));
              }
      

      我在 .net 核心应用程序中使用了它。

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 2020-08-03
        • 1970-01-01
        • 2017-10-14
        • 1970-01-01
        • 2017-10-19
        • 2012-05-27
        • 1970-01-01
        • 2019-04-11
        • 1970-01-01
        相关资源
        最近更新 更多