Thoughts caused by ASP.NET Core reading Response.Body
Thoughts caused by ASP.NET Core reading Response.Body Foreword A few days ago, a group of friends asked in the group how to solve some questions about my previous article “ASP.NET Core WebApi Return Results Unified Packaging Practice”. The main question was about the reading of Respouse. In the previous article “In-depth exploration of the correct way for ASP.NET Core to read Request.Body”, I have analyzed the reading problem of Request. Scenarios that need to read Response are also often encountered, such as reading output information or packaging the output. Results etc. Coincidentally, the reading of Response also has similar problems. In this article, we will analyze how to read the Body of Response. How to use How do we read streams in daily use? It’s very simple, just use StreamReader to read as follows public override void OnResultExecuted(ResultExecutedContext context) { //Restore the operation bit before operating the stream context.HttpContext.Response.Body.Position = 0; StreamReader stream = new StreamReader(context.HttpContext.Response.Body); string body = stream.ReadToEnd(); _logger.LogInformation(“body content:” + body); context.HttpContext.Response.Body.Position = 0; base.OnResultExecuted(context); } The code is very simple, just read it directly, but there is a problem with reading this way and an exception will be thrown System.ArgumentException: “Stream was not readable.”The exception information…
Thoughts caused by ASP.NET Core reading Response.Body
Thoughts caused by ASP.NET Core reading Response.Body Foreword A few days ago, a group of friends asked in the group how to solve some questions about my previous article “ASP.NET Core WebApi Return Results Unified Packaging Practice”. The main question was about the reading of Respouse. In the previous article “In-depth exploration of the correct way for ASP.NET Core to read Request.Body”, I have analyzed the reading problem of Request. Scenarios that need to read Response are also often encountered, such as reading output information or packaging the output. Results etc. Coincidentally, the reading of Response also has similar problems. In this article, we will analyze how to read the Body of Response. How to use How do we read streams in daily use? It’s very simple, just use StreamReader to read as follows public override void OnResultExecuted(ResultExecutedContext context) { //Restore the operation bit before operating the stream context.HttpContext.Response.Body.Position = 0; StreamReader stream = new StreamReader(context.HttpContext.Response.Body); string body = stream.ReadToEnd(); _logger.LogInformation(“body content:” + body); context.HttpContext.Response.Body.Position = 0; base.OnResultExecuted(context); } The code is very simple, just read it directly, but there is a problem with reading this way and an exception will be thrown System.ArgumentException: “Stream was not readable.”The exception information…