Answers for ".net core BeginRequest EndRequest"

C#
0

.net core BeginRequest EndRequest

//ref https://www.pluralsight.com/tech-blog/converting-http-modules-to-middleware/
//ref https://stackoverflow.com/questions/43403941/how-to-read-asp-net-core-response-body

app.UseMiddleware<RequestApplicationLogMiddleware>();
app.UseMiddleware<ResponseApplicationLogMiddleware>();

public async Task InvokeAsync(HttpContext context, IApplicationLog log)
{
  _session.Id=Guid.NewGuid().ToString();
  if (context.Request.Path.Value.Contains("api"))
  {
    log.SaveRqst(new { Header = context.Request.Headers, Data = context.Request.Body.ReadToEnd() }, context.Request.Path);
  }
  await _next(context);
}

 public async Task InvokeAsync(HttpContext context, IApplicationLog log)
 {
   //await _next(context);
   //log.SaveRsp(new { Header = context.Response.Headers, Data = context.Response.Body.ReadToEnd()}, context.Response.StatusCode.ToString(), context.Request.Path);

   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();
       if (context.Request.Path.Value.Contains("api"))
       {
         log.SaveRsp(new { Header = context.Response.Headers, Data = responseBody }, context.Response.StatusCode.ToString(), context.Request.Path);
       }

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

   }
   finally
   {
     context.Response.Body = originalBody;
   }
 }
Posted by: Guest on September-30-2020

C# Answers by Framework

Browse Popular Code Answers by Language