locked
Response is empty after logging in web api core RRS feed

  • Question

  • User-1350042179 posted

    Hi

    I have logging and control error in web api core.

    But when web api fails it doesn't return nothing..

    This is my middleware.

    public async Task Invoke(HttpContext context)
            {
                try
                {
    
                    if (logging.HalilitarTraza)
                    {
                        var logger = NLog.Web.NLogBuilder.ConfigureNLog("nLogTrace.config").GetCurrentClassLogger();
                        context.Request.EnableBuffering();
    
                        var buffer = new byte[Convert.ToInt32(context.Request.ContentLength)];
                        await context.Request.Body.ReadAsync(buffer, 0, buffer.Length);
                        var requestBody = Encoding.UTF8.GetString(buffer);
                        context.Request.Body.Seek(0, SeekOrigin.Begin);
    
                        var originalBodyStream = context.Response.Body;
    
                        var responseBody = new MemoryStream();
                        context.Response.Body = responseBody;
    
                        await next(context);
    
                        context.Response.Body.Seek(0, SeekOrigin.Begin);
                        var response = await new StreamReader(context.Response.Body).ReadToEndAsync();
                        context.Response.Body.Seek(0, SeekOrigin.Begin);
    
                        logger.Info(
                        "LLamada: " + (context.Request.Path.HasValue ? context.Request.Path.Value : string.Empty) +
                        " | Request: " + requestBody +
                        " | Response: " + response +
                        Environment.NewLine);
                        await responseBody.CopyToAsync(originalBodyStream);
                    }
                    else
                    {
                        await next(context);
                    }
    
                }
                catch (Exception ex)
                {
                    await HandleExceptionAsync(context, ex);
                }
                finally
                {
                    NLog.LogManager.Shutdown();
                }
            }

    Which calls: 

     private static async Task HandleExceptionAsync(HttpContext context, Exception ex)
            {
                var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
                var statusCode = (int)HttpStatusCode.InternalServerError;
                var exMessage = ex.Message;
    
                if (ex.InnerException != null)
                {
                    exMessage = exMessage + Environment.NewLine + ex.InnerException.Message;
    
                    if (ex.InnerException.InnerException != null)
                        exMessage = exMessage + Environment.NewLine + ex.InnerException.InnerException.Message;
                }
    
                if (ex is ArgumentException) statusCode = (int)HttpStatusCode.BadRequest;
                if (ex is AppException)
                {
                    var error = (AppException)ex;
                    if (error.Tipo == TipoException.ValidacionEntidad)
                    {
                        statusCode = (int)HttpStatusCode.BadRequest;
                    }
                }
    
                logger.Error(ex, $"Error ocurred on {DateTime.UtcNow.ToShortDateString()}");
    
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = statusCode;
                await SetErrorResultAsync(exMessage, context);
            }
    
            private async static Task SetErrorResultAsync(string mensaje, HttpContext context)
            {
                await context.Response.WriteAsync(new ErrorDto()
                {
                    Mensaje = mensaje
                }.ToString(), Encoding.UTF8);
            }

    The problem is that the service doesnt return the message that I enter in context.Response.WriteAsync

    Tuesday, April 7, 2020 10:52 PM

All replies

  • User-474980206 posted

    If an error is thrown, none of the code after await next() runs.

    Wednesday, April 8, 2020 12:55 AM