public async Task Invoke(HttpContext context, IApiLogger logger) { try { await _next(context); } catch (Exception ex) { logger.LogException(ex); } }
public async Task Invoke(HttpContext context, IApiLogger logger) { var currentBody = context.Response.Body; using (var memoryStream = new MemoryStream()) { //set the current response to the memorystream. context.Response.Body = memoryStream; try { await _next(context); } catch (Exception e) { logger.LogException(e); context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; } //reset the body context.Response.Body = currentBody; memoryStream.Seek(0, SeekOrigin.Begin); var readToEnd = new StreamReader(memoryStream).ReadToEnd(); var objResult = JsonConvert.DeserializeObject(readToEnd); if (context.Response.StatusCode > 400 && objResult == null) { var result = StausCodeMapper.Map((HttpStatusCode)context.Response.StatusCode); //Ideally this should be retrieved from System.Net.Mime.Mediatypes but application/json does not yet exist //So manually added the exact type with charset from an example response that's set by asp.net core (used the else part //of this if to see what asp.net core uses by default) //See: https://github.com/dotnet/corefx/issues/24895 context.Response.ContentType = "application / json; charset = utf - 8"; await context.Response.WriteAsync(JsonConvert.SerializeObject(result)); } else { await context.Response.WriteAsync(JsonConvert.SerializeObject(objResult)); } } }