public static IServiceCollection AddApplication(this IServiceCollection services, IConfiguration configuration) { services.AddAutoMapper(Assembly.GetExecutingAssembly()); //Services services.AddHttpContextAccessor(); //Customise default API behaviour services.Configure <ApiBehaviorOptions>(options => { //options.SuppressModelStateInvalidFilter = true; //Temporary Fix For Model State Validation options.InvalidModelStateResponseFactory = (context) => { var modelStates = context.ModelState; var validationException = new ValidationException() { Failures = modelStates .Where(x => x.Value.Errors.Count > 0) .ToDictionary( kvp => kvp.Key, kvp => kvp.Value.Errors.Select(e => !string.IsNullOrEmpty(e.ErrorMessage) ? e.ErrorMessage : e.Exception.Message) .ToArray() ) }; var result = validationException.ToErrorResponse(); return(new BadRequestObjectResult(result)); }; }); services.AddScoped <ICurrentUserService, CurrentUserService>(); return(services); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { var loggerFactory = LoggerFactory.Create(builder => { builder .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information); }); services .AddControllers() .AddJsonOptions( options => { options.JsonSerializerOptions.MaxDepth = 32; options.JsonSerializerOptions.AllowTrailingCommas = true; }); services .AddAuth(_configuration) .AddConfiguredAutomapper(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Octo_Api", Version = "v1" }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Type = SecuritySchemeType.Http, BearerFormat = "JWT", In = ParameterLocation.Header, Scheme = "bearer", Description = "Please insert JWT token into field" }); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] { } } }); }); services.AddCors(options => { options.AddPolicy("ClientPermission", policy => { policy.AllowAnyHeader() .AllowAnyMethod() .WithOrigins("http://localhost:3000") .AllowCredentials(); }); }); services.AddDbContext <DatabaseContext>(options => options .UseLoggerFactory(loggerFactory) .UseSqlServer("Data Source=.;Initial Catalog=UpgradedOcto;Integrated Security=True") // TODO: abstract to config .EnableSensitiveDataLogging(), //.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking), ServiceLifetime.Transient, ServiceLifetime.Transient ); services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = ctx => { var exception = new ValidationException(ExceptionMapping.None, "", ctx.ModelState); try { ctx.HttpContext.Response.StatusCode = 400; return(new BadRequestObjectResult(exception.ToErrorResponse())); } catch (Exception ex) { Console.WriteLine(ex.Message); } return(new BadRequestObjectResult(exception.ToErrorResponse())); }; }); services .AddScoped <IBlobStorageService, BlobStorageService>() .AddScoped <IMailerService, MailerService>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // database var connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext <ApplicationDbContext>(options => { options.UseNpgsql(connectionString, sqlOptions => { sqlOptions.MigrationsAssembly(typeof(ApplicationDbContext).GetTypeInfo().Assembly.GetName().Name); sqlOptions.EnableRetryOnFailure(5, TimeSpan.FromSeconds(30), errorCodesToAdd: null); }); }); // automapper services.AddAutoMapper(typeof(BlogMappings)); // swagger services.AddApiVersioning(options => { options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = new ApiVersion(1, 0); options.ReportApiVersions = true; }); services.AddVersionedApiExplorer(options => options.GroupNameFormat = "'v'VVV"); services.AddTransient <IConfigureOptions <SwaggerGenOptions>, ConfigureSwaggerOptions>(); services.AddSwaggerGen(); // controllers services.AddControllers(options => { options.Filters.Add(typeof(CustomExceptionFilter)); }) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0) .AddFluentValidation(options => options.RegisterValidatorsFromAssemblyContaining <RegisterDtoValidator>()) .AddNewtonsoftJson(options => { options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; }); // cors services.AddCors(); // repositories services.AddScoped <IAuthRepository, AuthRepository>(); services.AddScoped <IUserRepository, UserRepository>(); // api behaviour services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = context => { var modelState = context.ModelState; var failures = modelState .Where(x => x.Value.Errors.Count > 0) .ToDictionary( kvp => kvp.Key, kvp => kvp.Value.Errors.Select(e => !string.IsNullOrEmpty(e.ErrorMessage) ? e.ErrorMessage : e.Exception.Message) .ToArray() ); var validationException = new ValidationException { Failures = failures }; var result = validationException.ToErrorResponse(); return(new BadRequestObjectResult(result)); }; }); // services services.AddScoped <IAuthService, AuthService>(); services.AddScoped <ICurrentUserService, CurrentUserService>(); services.AddScoped <IUsersService, UsersService>(); services.AddScoped <ITokenHandlerService, TokenHandlerService>(); services.AddHttpContextAccessor(); // filters services.AddScoped <LogUserActivityFilter>(); // authentication services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CustomAuthSchemes.BearerAuthScheme; options.DefaultChallengeScheme = CustomAuthSchemes.BearerAuthScheme; }).AddTokenAuthentication(CustomAuthSchemes.BearerAuthScheme, "Bearer Authentication Scheme", options => { }); // settings services.Configure <ApplicationSettings>(Configuration.GetSection(nameof(ApplicationSettings))); }