public static IServiceCollection AddApplicationService(this IServiceCollection services) { services.AddScoped <ITokenService, TokenService>(); services.AddScoped services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IBasketRepository, BasketRepository>(); services.AddScoped(typeof(IGenericRepository <>), (typeof(GenericRepository <>))); services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = actionContext => { var errors = actionContext.ModelState .Where(e => e.Value.Errors.Count > 0).SelectMany(x => x.Value.Errors) .Select(x => x.ErrorMessage).ToArray(); var errorResponse = new ApiValidationErrorResponse { Errors = errors }; return(new BadRequestObjectResult(errorResponse)); }; }); return(services); }
public async Task <ActionResult <UserDto> > Register(RegisterDto registerDto) { if (CheckEmailExists(registerDto.Email).Result.Value) { var emailInUseResponse = new ApiValidationErrorResponse { Errors = new [] { "Email address is in use" } }; var badRequestObject = new BadRequestObjectResult(emailInUseResponse); return(badRequestObject); } var badRequestCode = (int)HttpStatusCode.BadRequest; var user = new AppUser { DisplayName = registerDto.DisplayName, Email = registerDto.Email, UserName = registerDto.Email }; var result = await _userManager.CreateAsync(user, registerDto.Password); if (!result.Succeeded) { return(BadRequest(new ApiResponse(badRequestCode))); } var userDto = new UserDto { Email = user.Email, Token = _tokenService.CreateToken(user), DisplayName = user.DisplayName }; return(userDto); }
public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services.AddScoped <IDashBoardService, DashBoardService>(); services.AddScoped <IContentService, ContentService>(); services.AddScoped <IUserProfileService, UserProfileService>(); services.AddScoped <ICampaignAssignmentService, CampaignAssignmentService>(); services.AddScoped <ISchedulerService, SchedulerService>(); services.AddScoped <IEmailService, EmailService>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <ITokenRepository, TokenRepository>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IAccountService, AccountService>(); services.AddScoped <ITokenService, TokenService>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped(typeof(IGenericRepository <>), (typeof(GenericRepository <>))); services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = actionContext => { var errors = actionContext.ModelState .Where(e => e.Value.Errors.Count > 0) .SelectMany(x => x.Value.Errors) .Select(x => x.ErrorMessage).ToArray(); var errorResponse = new ApiValidationErrorResponse { Errors = errors }; return(new BadRequestObjectResult(errorResponse)); }; }); return(services); }
public static IServiceCollection AddApplicationServices(this IServiceCollection services) { services.AddSingleton <IResponseCacheService, ResponseCacheService>(); services.AddScoped <IPhotoService, PhotoService>(); services.AddScoped <ITokenService, TokenService>(); services.AddScoped <IOrderService, OrderService>(); services.AddScoped <IPaymentService, PaymentService>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); // Tiêm logger cho class ExceptionMiddleware services.AddSingleton <Microsoft.Extensions.Logging.ILogger>(provider => provider.GetRequiredService <Microsoft.Extensions.Logging.ILogger <ExceptionMiddleware> >()); //Transient:Một thể hiện mới luôn được tạo, mỗi khi được yêu cầu. //Scoped: Tạo một thể hiện mới cho tất cả các scope (Mỗi request là một scope). Trong scope thì service được dùng lại //Singleton: Service được tạo chỉ một lần duy nhất. services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IBasketRepository, BasketRepository>(); services.AddScoped(typeof(IGenericRepository <>), (typeof(GenericRepository <>))); //config bad request trả về theo kiểu ApiValidationErrorResponse services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = actionContext => { var errors = actionContext.ModelState .Where(e => e.Value.Errors.Count > 0) .SelectMany(x => x.Value.Errors) .Select(x => x.ErrorMessage).ToArray(); var errorResponse = new ApiValidationErrorResponse { Errors = errors }; return(new BadRequestObjectResult(errorResponse)); }; }); return(services); }
//the following function should be static as well since the class is static //this function return a collection of services we will write in it //we should mention the keyword "this" before the below parameter, so that "return service" will mean to return all the Services written in this function //this class is function in the startup.cs file public static IServiceCollection AddApplicationServices(this IServiceCollection services) { //add the interfaces/implementations services: //when it comes to "caching" concept, it is better to register this service as singleton //so it is available any time for any user: services.AddSingleton <IResponseCacheService, ResponseCacheService>(); //when the user logins/registers, he gets a token to send with each subsequent https request. //to generate a token, we created the ITokenService interface and its implementation in TokenService //(in Core project, interfaces folder and in Infrastructure project, services folder) //and injected the service in the AccountController. //add the interface and its implementation in startup file (or in AppicationServicesExtensions) //and add the Authentication service with tokens in startup file (or in the IdentityServiceExtensions) services.AddSingleton <ITokenService, TokenService>(); //services.AddScoped<IProductRepository, ProductRepository>(); //that service is not used anymore since we are using the below IgenericRepository interface and its GenericRepository Implementation //add the generic interface/implementation service: services.AddScoped(typeof(IGenericRepository <>), (typeof(GenericRepository <>))); //and we used Redis to store customers' baskets and in it basket items. //we used for that IBasketRepository and BasketRepository so we need to register these here: //(redis connection string service is in startup.cs) services.AddScoped <IBasketRepository, BasketRepository>(); //add the IOrderService and OrderService as scoped here: services.AddScoped <IOrderService, OrderService>(); //add the IPyamentService nd PaymentService where we deal with the third party payment processor "Stripe": services.AddScoped <IPaymentService, PaymentService>(); //the services realted to submit a message from the contact us page: services.AddScoped <IMessageService, MessageService>(); //add this service to shape the validation-based bad request errors as we designed in the ApiValidationErrorResponse class in the Errors folder: //indeed, the services order in here is not important, but there are alawys exceptions, //the following service should be after the services.AddControllers(); service in the startup file: services.Configure <ApiBehaviorOptions>(options => { //InvalidModelStateResponseFactory is from where we generate the Invalid Model errors options.InvalidModelStateResponseFactory = ActionContext => { //errors will be an array //using .where, we figure out if there are errors generated or no ! //then select all the errors //then select the error messages from these errors //then save them as an array var errors = ActionContext.ModelState .Where(e => e.Value.Errors.Count > 0) .SelectMany(x => x.Value.Errors) .Select(x => x.ErrorMessage) .ToArray(); //now initialize an instance of the ApiValidationErrorResponse class //it has an attribute IEnumerable<string> called "Errors", fill it with the previously created "errors" array var errorResponse = new ApiValidationErrorResponse { Errors = errors }; //now return the ApiValidationErrorResponse instance (errorResponse) in a bad request result return(new BadRequestObjectResult(errorResponse)); }; }); return(services); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var dbConnectionString = _configuration.GetConnectionString("DefaultConnection"); var dbIdentityConnectionString = _configuration.GetConnectionString("IdentityConnection"); Console.WriteLine(dbConnectionString); Console.WriteLine(dbIdentityConnectionString); services.AddCors(opt => { opt.AddPolicy("CorsPolicy", policy => { policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200"); }); }); services.AddControllers() .AddJsonOptions(opt => { opt.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); services.AddDbContext <StoreContext>(x => { x.UseSqlServer("Server=VADER\\SQL2012;Database=Ecommerce;User=sa;Pwd=Pa33w0rd;"); }); services.AddDbContext <AppIdentityDbContext>(x => { x.UseSqlServer("Server=VADER\\SQL2012;Database=EcommerceIdentity;User=sa;Pwd=Pa33w0rd;"); }); services.AddSingleton <IConnectionMultiplexer>(c => { var configuration = ConfigurationOptions.Parse(_configuration.GetConnectionString("Redis"), true); return(ConnectionMultiplexer.Connect(configuration)); }); services.AddScoped <ITokenService, TokenService>(); services.AddScoped <IOrderService, OrderService>(); services.AddScoped <IProductRepository, ProductRepository>(); services.AddScoped <IBasketRepository, BasketRepository>(); services.AddScoped <IOrderRepository, OrderRepository>(); services.AddScoped <IDeliveryMethodRepository, DeliveryMethodRepository>(); services.AddScoped <IProductBrandRepository, ProductBrandRepository>(); services.AddScoped <IProductTypeRepository, ProductTypeRepository>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped <IPaymentService, PaymentService>(); services.AddAutoMapper(typeof(MappingProfiles)); services.AddIdentityServices(_configuration); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "api", Version = "v1" }); var securitySchema = new OpenApiSecurityScheme { Description = "JWT Auth Bearer Scheme", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; c.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement { { securitySchema, new[] { "Bearer" } } }; c.AddSecurityRequirement(securityRequirement); }); services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = actionContext => { var errors = actionContext.ModelState .Where(x => x.Value.Errors.Count > 0) .SelectMany(x => x.Value.Errors) .Select(x => x.ErrorMessage) .ToArray(); var errorResponse = new ApiValidationErrorResponse { Errors = errors }; return(new BadRequestObjectResult(errorResponse)); }; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSingleton <IConnectionMultiplexer>(c => { var configuration = ConfigurationOptions.Parse(Configuration.GetConnectionString("Redis"), true); return(ConnectionMultiplexer.Connect(configuration)); }); //Identity Config var builder = services.AddIdentityCore <AppUser>(); builder = new IdentityBuilder(builder.UserType, builder.Services); builder.AddEntityFrameworkStores <AppIdentityDbContext>(); builder.AddSignInManager <SignInManager <AppUser> >(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Token:Key"])), ValidIssuer = Configuration["Token:Issuer"].ToString(), ValidateIssuer = true, ValidateAudience = false }; }); services.AddSingleton <IResponseCacheService, ResponseCacheService>(); services.AddTransient <IProductRepository, ProductRepository>(); services.AddScoped <IBasketRepository, BasketRepository>(); services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>)); services.AddTransient <ITokenService, TokenService>(); services.AddTransient <IOrderService, OrderService>(); services.AddTransient <IPaymentService, PaymentService>(); services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddAutoMapper(typeof(MappingProfile)); //Configuration when api parameter not valid. E.g: type int ==> fsafdss services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = actionContext => { var errors = actionContext.ModelState.Where(e => e.Value.Errors.Count > 0) .SelectMany(x => x.Value.Errors) .Select(x => x.ErrorMessage).ToArray(); var errorResponse = new ApiValidationErrorResponse { Errors = errors }; return(new BadRequestObjectResult(errorResponse)); }; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" }); var securitySchema = new OpenApiSecurityScheme { Description = "JWT Auth Bearer Schema", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; c.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement { { securitySchema, new[] { "Bearer" } } }; c.AddSecurityRequirement(securityRequirement); }); services.AddCors(opt => { opt.AddPolicy("CorsPolicy", policy => { policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200"); }); }); }
public static IServiceCollection RequestResponseServices(this IServiceCollection services, IConfiguration configuration) { services.AddAutoMapper(typeof(MappingProfiles)); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(opt => { opt.RequireHttpsMetadata = false; opt.SaveToken = true; opt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Token:Key"])), ValidIssuer = configuration["Token:Issuer"], ValidateIssuer = true, ValidateAudience = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; }); services.AddAuthorization(); services.AddControllers().AddFluentValidation(cfg => { cfg.RegisterValidatorsFromAssemblyContaining <Startup>(); }).AddJsonOptions(opts => { opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }); services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = actionContext => { var errors = actionContext.ModelState .Where(e => e.Value.Errors.Count > 0) .SelectMany(x => x.Value.Errors) .Select(x => x.ErrorMessage) .ToArray(); var errorResponse = new ApiValidationErrorResponse { Errors = errors }; return(new BadRequestObjectResult(errorResponse)); }; }); services.AddCors(opt => { opt.AddPolicy("CorsPolicy", policy => { policy .AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin() .WithExposedHeaders("WWW-Authenticate"); }); }); return(services); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddDbContext <AppDbContext>(x => { x.UseSqlite(Configuration.GetConnectionString("DbConnection")); }); /***************************************************************** * to use UserManager & IdentityRole in application: * Add service for type 'Microsoft.AspNetCore.Identity.UserManager: * - .AddIdentityCore<AppUser>() * Add IdentityRole service in Application: * - .AddRoles<IdentityRole>() * to avoid error :Unable to resolve service for type 'Microsoft.AspNetCore.Identity.IUserStore`1 * - AddEntityFrameworkStores<AppDbContext>() * Add SignInManager Service to Login Action * - .AddSignInManager<SignInManager<AppUser>>() * to inject SignInManager service need to inject another service : * - services.AddAuthentication() * to use Microsoft.AspNetCore.Identity Token provider to use function like:UserManager.GenerateEmailConfirmationTokenAsync() * - .AddDefaultTokenProviders() */ services.AddIdentityCore <AppUser>() .AddRoles <IdentityRole>() .AddEntityFrameworkStores <AppDbContext>() .AddDefaultTokenProviders() .AddSignInManager <SignInManager <AppUser> >(); /********************************************************************/ // Add Mapping Tools services.AddAutoMapper(typeof(MappingProfiles)); // add JWT Service services.AddScoped <ITokenService, TokenService>(); services.AddIdentityServices(Configuration); // to use EmailSmsSender Service in API project services.AddScoped <EmailSmsSenderService>(); // API/Extensions/SwaggerServiceExtensions.cs services.AddSwaggerDocumentation(Configuration); //************************************************ override the behavior of ``[ ApiController ] // Configer the ApiBehaviorOptions type service services.Configure <ApiBehaviorOptions>(options => { // pass some option what we want configer options.InvalidModelStateResponseFactory = actionContext => { /*inside the actionContext is where we can get our model state errors and that's what the API attribute is * using to populate any errors that are related to validation and add them into a model state dictionar*/ /*extract the errors if there are any and populates the error messages into an array and * that's the array will pass into our ApiValidationErrorResponse class into the errors property */ var errors = actionContext.ModelState /* ModelState is a dictionary type of object. */ .Where(e => e.Value.Errors.Count > 0) /* check if here any Error */ .SelectMany(x => x.Value.Errors) /* select all of the errors */ .Select(x => x.ErrorMessage).ToArray(); /* select just the error messages */ var errorResponse = new ApiValidationErrorResponse { Errors = errors }; return(new BadRequestObjectResult(errorResponse)); /* pass ApiValidationErrorResponse with all errors*/ }; }); // Add Global Function to use it in all apps services.AddScoped <GlobalFunctions>(); }
public void ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(); services.AddControllers(); services.AddCors(opt => { opt.AddPolicy("CustomCorsPolicy", policy => { policy .AllowAnyHeader() .AllowAnyMethod() //.AllowCredentials() .AllowAnyOrigin(); }); }); services.AddSingleton <IConnectionMultiplexer>(c => { var configuration = ConfigurationOptions.Parse(Configuration .GetConnectionString("Redis"), true); return(ConnectionMultiplexer.Connect(configuration)); }); services.AddMvc(m => { // e.g application/xml m.ReturnHttpNotAcceptable = true; }) .SetCompatibilityVersion(CompatibilityVersion.Latest) .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = actionContext => { var errors = actionContext.ModelState .Where(e => e.Value.Errors.Count > 0) .SelectMany(x => x.Value.Errors) .Select(x => x.ErrorMessage).ToArray(); var errorResponse = new ApiValidationErrorResponse { Errors = errors }; return(new BadRequestObjectResult(errorResponse)); }; }); services.AddMediatR(typeof(BaseEntity)); services.AddAutoMapper(typeof(MappingProfiles)); services.AddDataPersistenceServices(Configuration); services.AddCustomIdentityServices(Configuration); services.AddCustomSwaggerServices(); services.AddCustomApiVersioning(); services.AddScoped <IPictureUrlResolver, PictureUrlResolver>(); services.AddScoped <ITokenService, TokenService>(); services.AddApplicationServices(Configuration); }
private ActionResult <UserDto> BadRequestObjectResult(ApiValidationErrorResponse apiValidationErrorResponse) { return(BadRequest(apiValidationErrorResponse)); }