// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration).CreateLogger(); services.AddHttpClient(); services.AddScoped <IRestaurant, RestaurantService>(); services.AddScoped <IRestaurantInfo, RestaurantInfoService>(); services.AddMemoryCache(); services.AddSingleton <ICache, InMemoryCacheService>(); services.AddScoped <JwtToken>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) }; }); services.AddControllers() .ConfigureApiBehaviorOptions(o => { // Disable `ClientErrorResultFilter` o.SuppressMapClientErrors = true; // Custom response format for model validation and binding errors o.InvalidModelStateResponseFactory = context => { var dto = new CustomErrorDto { Error = context.ModelState.First().Value.Errors.First().ErrorMessage.Split('|')[0], StatusCode = 400, RequestId = context.HttpContext.TraceIdentifier }; return(new ObjectResult(dto) { StatusCode = dto.StatusCode }); }; }) .AddJsonOptions(o => { o.JsonSerializerOptions.WriteIndented = true; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "RestaurantInformation.Api", Version = "v1" }); }); }
void UseExceptionBinder_Local(IApplicationBuilder app, bool isDebug) { app.UseMvcExceptionHandler((s) => { s.IsDebug = isDebug; s.DefaultHttpCode = 500; s.CanBindByHttpCode = true; s.Host = AppSettings.EXTERNAL_URL; s.JsonSerializerSettings.Formatting = isDebug ? Formatting.Indented : Formatting.None; s.FilterAfterDTO = async(errorContext) => { var errorDto = new CustomErrorDto(); errorDto.Error.Message = errorContext.ResponseDTO.Message; errorDto.Error.ErrorKey = errorContext.ResponseDTO.ErrorKey; if (isDebug) { errorDto.Error.DebugUrl = errorContext.ResponseDTO.DebugUrl; } var jsonStr = JsonConvert.SerializeObject(errorDto, s.JsonSerializerSettings); var resp = errorContext.HttpContext.Response; resp.ContentType = "application/json"; resp.StatusCode = errorContext.ErrorInfo.HttpCode ?? 500; await resp.WriteAsync(jsonStr); return(true); }; s.Mapping((builder) => { //Регистрируем исключение по http коду builder.Register( httpCode: 500, errorKey: "InternalServerError" ); builder.Register( httpCode: 403, errorKey: "Forbidden" ); builder.Register <UnauthorizedException>( httpCode: 401, errorKey: "Unauthorized" ); builder.Register( httpCode: 400, errorKey: "BadRequest" ); builder.RegisterAllAssignable <Exception>( httpCode: 500, errorKeyPrefix: "" ); }); }); }