簡體   English   中英

在ActionFilterAttribute中讀取Asp.Net核心響應主體

[英]Read Asp.Net Core Response body in ActionFilterAttribute

我使用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中的響應作為Extension方法獲取,如下所示:

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結果/視圖結果,則無需讀取整個響應流。 只需序列化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("...");
        }
    }

我知道已經有了答案,但我想補充一點,問題是MVC管道在運行ActionFilter時沒有填充Response.Body ,因此您無法訪問它。 Response.Body由MVC middleware填充。

如果您想閱讀Response.Body那么您需要創建自己的自定義中間件,以便在填充Response對象時攔截調用。 有很多網站可以告訴你如何做到這一點。 這里有一個例子。

正如在另一個答案中所討論的,如果您想在ActionFilter執行此操作,則可以使用context.Result來訪問信息。

要在ASP.NET Core過濾器管道中 記錄整個請求和響應 ,可以使用Result過濾器屬性

    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;
            }

        } 

你也可以......

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核心應用程序中使用了它。

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM