public async Task Invoke(HttpContext context) { await next(context); var response = new CommonAPIResponse(); if (context.Items["exception"] != null) { var errorResponse = ApiErrorResponseFactory.Create((Exception)context.Items["exception"]); errorResponse.CorrelationId = context.Items["correlationId"]?.ToString() ?? string.Empty; context.Response.StatusCode = errorResponse.StatusCode; response.Result = errorResponse; } else { try { response.Result = JsonConvert.DeserializeObject <object>(context.Items["responseMessage"].ToString()); } catch (Exception) { response.Result = new ApiErrorResponse(500, "Invalid response format"); context.Response.StatusCode = 500; } } context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(response)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = (context) => { var result = ApiErrorResponseFactory.Build(context.ModelState); return(new BadRequestObjectResult(result)); }; }); services.AddTransient <IUsersRepository, InMemoryUsersRepository>(); }