Пример #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            DataAccessLayerBase.Configuration = Configuration;

            services.AddHttpContextAccessor();
            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();

            services.Configure <TokenSettings>(Configuration.GetSection("tokenSettings"));

            var token  = Configuration.GetSection("tokenSettings").Get <TokenSettings>();
            var secret = Encoding.ASCII.GetBytes(token.Secret);

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
                    ValidIssuer      = token.Issuer,
                    ValidAudience    = token.Audience,
                    ValidateIssuer   = false,
                    ValidateAudience = false
                };
            });

            services.AddMvc(options =>
            {
                options.Filters.Add <ApiExceptionFilter>();
            }).AddJsonOptions(x =>
            {
                x.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                x.SerializerSettings.NullValueHandling     = NullValueHandling.Ignore;
                x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                x.SerializerSettings.Formatting            = Formatting.Indented;
                x.SerializerSettings.ContractResolver      = new DefaultContractResolver();
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddCors(c => c.AddPolicy("AllowAllHeaders", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(nameof(v1), new Info()
                {
                    Title       = $"Roulette Api {nameof(v1)}",
                    Description = "Service for managing virtual roulette game",
                    Version     = nameof(v1)
                });

                var currentDir = new DirectoryInfo(AppContext.BaseDirectory);
                foreach (var xmlCommentFile in currentDir.EnumerateFiles("Roulette.*.xml"))
                {
                    c.IncludeXmlComments(xmlCommentFile.FullName);
                }
                c.DescribeAllEnumsAsStrings();

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme {
                    In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() },
                });
            });

            services.AddTransient <IDBProvider, DBProvider>();
            services.AddTransient <ISignInManager, SignInManager>();

            var container = new ContainerBuilder();

            CommandServices.RegisterServices(container, services);
            QueryServices.RegisterServices(container, services);

            container.Populate(services);

            return(new AutofacServiceProvider(container.Build()));
        }
Пример #2
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(op =>
            {
                op.Filters.Add <ValidationFilter>();
                op.RespectBrowserAcceptHeader = true;
            })
            .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
            .AddXmlSerializerFormatters();

            services.AddTransient <TokenService, TokenService>();
            services.AddTransient <TaxAndShippingCalculationService, TaxAndShippingCalculationService>();

            services.AddSwaggerGen(x =>
            {
                x.ExampleFilters();

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                x.IncludeXmlComments(xmlPath);

                x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Name = "Authorization",
                    Type = SecuritySchemeType.ApiKey,
                    In   = ParameterLocation.Header,
                });
                x.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] {}
                    }
                });
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.SaveToken                 = true;
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer   = true,
                    ValidateAudience = true,
                    ValidAudience    = Configuration["Jwt:Audience"],
                    ValidIssuer      = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });


            services.AddSwaggerExamplesFromAssemblyOf <Startup>();

            services.AddMvc(op =>
            {
                op.Filters.Add <ApiExceptionAttribute>();
            })
            .AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining <Startup>());

            services.AddAutoMapper(typeof(Startup));

            services.AddDbContext <ApplicationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            var container = new ContainerBuilder();

            CommandServices.RegisterServices(container, services);
            QueryServices.RegisterServices(container, services);

            container.Populate(services);

            return(new AutofacServiceProvider(container.Build()));
        }