示例#1
0
        public static IServiceCollection AddApplicationService(this IServiceCollection services)
        {
            services.AddScoped <IProductRepository, ProductRepository>();

            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));

            services.AddScoped <IBasketRepository, BasketRepository>();

            services.AddScoped <ITokenService, TokenService>();

            services.AddScoped <IOrderService, OrderService>();

            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 ApiValidationError()
                    {
                        Errors = errors
                    };

                    return(new BadRequestObjectResult(errorResponse));
                };
            });

            return(services);
        }
示例#2
0
        public static IServiceCollection AddAplicationServices(this IServiceCollection services)
        {
            //Interfaz Producto repositorio creado
            services.AddScoped <IproductRepository, ProductRepository>();
            //Interfaz Repositorio generico Creado
            services.AddScoped(typeof(IGenericRepository <>), (typeof(GenericRepository <>)));

            //configuracion del servicio //Bad request/five
            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 ApiValidationError
                    {
                        Errors = errors
                    };//Bad request/five
                    return(new BadRequestObjectResult(errorResponse));
                };
            });
            return(services);
        }
示例#3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddScoped<IProductRepository, ProductRepository>(); // object will be available for a request only - transient -> method, signleton - lifetime
            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));
            // configure api error behaviour in case of bad request error
            // we are now sending our own error object and also sending all the errors with that.

            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    var errors        = actionContext.ModelState.Where(f => f.Value.Errors.Count() > 0).SelectMany(s => s.Value.Errors).Select(s => s.ErrorMessage).ToArray();
                    var errorResponse = new ApiValidationError
                    {
                        Errors = errors
                    };

                    return(new BadRequestObjectResult(errorResponse));
                };
            });

            services.AddAutoMapper(typeof(MappingProfile));
            services.AddControllers();
            services.AddDbContext <StoreContext>(option => option.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo {
                    Version = "v1", Title = "Ecom Trial"
                });
            });
            services.AddCors(m => m.AddPolicy("CorsPolicy", p =>
            {
                p.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200");
            }));
        }
        public static string ToDebugMessage(this ApiValidationError error)
        {
            if (error == null)
            {
                return("<null>");
            }

            if (error.ErrorKey == null)
            {
                return("<null-key>");
            }

            if (error.ErrorKey.Length == 0)
            {
                return("<empty-key>");
            }

            var result = error.ErrorKey;

            if (error.ErrorParameters != null)
            {
                result += $"({string.Join(", ", error.ErrorParameters)})";
            }

            if (!string.IsNullOrWhiteSpace(error.PropertyPath))
            {
                result += $" on {error.PropertyPath}";
            }

            return(result);
        }
        public static IServiceCollection AddApplicationServices(this IServiceCollection services)
        {
            services.AddScoped <ITokenService, TokenService>();
            services.AddScoped <IProductRepository, ProductRepository>(); // appropriate for injecting services to be available in our application
            services.AddScoped <IBasketRepository, BasketRepository>();
            // Way to inject the generic service. As we don't know the type of the service
            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 ApiValidationError
                    {
                        Errors = errors
                    };
                    return(new BadRequestObjectResult(errorResponse));
                };
            });
            return(services);
        }
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped <IToken, TokenService>();
            services.AddScoped <IOrderService, OrderService>();
            services.AddSingleton <ICacheResponse, CacheResponseService>();
            services.AddScoped <IPaymentService, PaymentService>();
            services.AddScoped <IProductRepository, ProductRepository>();
            services.AddScoped <IBasketRepo, BasketRepo>();
            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));
            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 model = new ApiValidationError
                    {
                        Errors = errors
                    };
                    return(new BadRequestObjectResult(model));
                };
            });

            return(services);
        }
示例#7
0
        public static IServiceCollection AddApplicationServices(this IServiceCollection services)
        {
            //Is there a way to automatically register these services?
            //Repo
            services.AddScoped <IUserRepo, UserRepo>();
            services.AddScoped <IChallengeRepo, ChallengeRepo>();
            services.AddScoped <IGoalRepo, GoalRepo>();
            services.AddScoped <IFriendRequestRepo, FriendRequestRepo>();
            services.AddScoped <IFriendshipRepo, FriendshipRepo>();
            services.AddScoped <ICompetitionRepo, CompetitionRepo>();
            services.AddScoped <IParticipantRepo, ParticipantRepo>();
            services.AddScoped <IParticipationRequestRepo, ParticipationRequestRepo>();
            services.AddScoped <IInvitationRepo, InvitationRepo>();
            services.AddScoped <IAdminRepo, AdminRepo>();
            services.AddScoped <IAdminRequestRepo, AdminRequestRepo>();

            //Services
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IGoalService, GoalService>();
            services.AddScoped <IFriendRequestService, FriendRequestService>();
            services.AddScoped <IFriendshipService, FriendshipService>();
            services.AddScoped <ICompetitionService, CompetitionService>();
            services.AddScoped <IParticipantService, ParticipantService>();
            services.AddScoped <IParticipationRequestService, ParticipationRequestService>();
            services.AddScoped <IInvitationService, InvitationService>();
            services.AddScoped <IAdminService, AdminService>();
            services.AddScoped <IAdminRequestService, AdminRequestService>();
            services.AddScoped <IMappingService, MappingService>();

            //Utilities
            services.AddScoped <ITokenUtility, TokenUtility>();
            services.AddScoped <IPasswordUtility, PasswordUtility>();

            //Configures default ApiController behavior so we can more easily handle validation errors
            //Validation errors are pulled from model state and put into single array that is returned on our custom error
            //Must come after .AddControllers()
            //https://www.udemy.com/course/learn-to-build-an-e-commerce-app-with-net-core-and-angular/learn/lecture/18137238#overview
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    //ModelState is dictionary object
                    var errors = actionContext.ModelState
                                 .Where(e => e.Value.Errors.Count > 0)
                                 .SelectMany(x => x.Value.Errors)
                                 .Select(x => x.ErrorMessage).ToArray();

                    var errorResponse = new ApiValidationError(errors);
                    return(new BadRequestObjectResult(errorResponse));
                };
            });

            return(services);
        }
示例#8
0
        public static string ToErrorString(this ApiValidationError error)
        {
            var result = $"[{error.ErrorKey ?? "-"}]";

            if (!string.IsNullOrWhiteSpace(error.PropertyPath))
            {
                result += $" ({error.PropertyPath})";
            }

            if (!string.IsNullOrWhiteSpace(error.LocalizedMessage))
            {
                result += $" {error.LocalizedMessage}";
            }

            return(result);
        }
示例#9
0
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var apiException = new ModelValidationException();
                foreach (var modelStateKey in context.ModelState.Keys)
                {
                    var modelStateVal = context.ModelState[modelStateKey];


                    var validationExceptions = new ApiValidationError()
                    {
                        Key    = modelStateKey,
                        Values = modelStateVal.Errors.Select(x => x.ErrorMessage).ToArray(),
                    };
                    apiException.apiValidationErrors.Add(validationExceptions);
                }
                throw apiException;
            }
        }
示例#10
0
        public static IServiceCollection AddApplicationServices(this IServiceCollection services)
        {
            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));

            services.AddScoped <IProductRepository, ProductRepository>();

            services.AddScoped <IBasketRepository, BasketRepository>();

            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 ApiValidationError {
                        Errors = errors
                    };

                    return(new BadRequestObjectResult(errorResponse));
                };
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "API Document", Version = "v1"
                });
            });

            services.AddCors(opt =>
            {
                opt.AddPolicy("corsPolicy", policy =>
                              { policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin(); });
            });

            return(services);
        }
        public static IServiceCollection AddApplicationServices(this IServiceCollection services)
        {
            services.AddScoped <IProductRepository, ProductRepository>();
            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = action => {
                    var errors = action.ModelState.Where(x => x.Value.Errors.Count > 0)
                                 .SelectMany(e => e.Value.Errors)
                                 .Select(v => v.ErrorMessage).ToArray();

                    var validationErrors = new ApiValidationError(400)
                    {
                        ValidationErrors = errors
                    };

                    return(new BadRequestObjectResult(validationErrors));
                };
            }
                                                    );

            return(services);
        }
示例#12
0
        public static IServiceCollection AddAppServices(this IServiceCollection services)
        {
            services.AddScoped <IServiceRepo, ServiceRepo>();
            services.AddScoped(typeof(IGenericRepo <>), (typeof(GenericRepo <>)));
            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 ApiValidationError
                    {
                        Errors = errors
                    };

                    return(new BadRequestObjectResult(errorResponse));
                };
            });

            return(services);
        }
        // When exdending class don`t forget to use the class as static and pass 'this' with the class that will be extended
        public static IServiceCollection AddApplicationServices(this IServiceCollection services)
        {
            services.AddScoped <IClientRepository, ClientRepository>();
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    var errors = actionContext.ModelState
                                 .Where(x => x.Value.Errors.Count > 0)
                                 .SelectMany(y => y.Value.Errors)
                                 .Select(z => z.ErrorMessage)
                                 .ToArray();

                    var errorResponse = new ApiValidationError
                    {
                        Errors = errors
                    };

                    return(new BadRequestObjectResult(errorResponse));
                };
            });

            return(services);
        }
示例#14
0
 protected IHttpActionResult ValidationError(ApiValidationError error)
 {
     return(new ValidationErrorResult(ApiValidationResult.Failure(error), this));
 }