Esempio n. 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add Cors service.
            services.AddCors(options => options
                             .AddPolicy("CorsPolicy", p => p
                                        .AllowAnyOrigin()
                                        .AllowAnyMethod()
                                        .AllowAnyHeader()
                                        )
                             );

            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

            //var builder = services.AddIdentityServer()
            //    //.AddSigningCredential(cert)
            //    .AddDeveloperSigningCredential()
            //    .AddInMemoryClients(Config.GetClients())
            //    .AddInMemoryIdentityResources(Config.GetIdentityResources())
            //    .AddInMemoryApiResources(Config.GetApiResources())
            //    .AddProfileService<IdentityProfileService>()
            //    .AddResourceOwnerValidator<IdentityResourceOwnerPasswordValidator>();

            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));
            services.Configure <AppConnections>(Configuration.GetSection("ConnectionStrings"));

            services.AddSingleton <IConfiguration>(Configuration);

            var appSettings = new AppSettings();

            Configuration.Bind("AppSettings", appSettings);
            services.AddSingleton <AppSettings>(appSettings);

            var appConnections = new AppConnections();

            Configuration.Bind("ConnectionStrings", appConnections);
            services.AddSingleton <AppConnections>(appConnections);

            var authenticationCfg = new AuthenticationCfg();

            Configuration.Bind("Authentication", authenticationCfg);
            services.AddSingleton <AuthenticationCfg>(authenticationCfg);

            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <ICategoryRepository, CategoryRepository>();
            services.AddScoped <IAudioBookRepository, AudioBookRepository>();

            //services.AddScoped<IFileProvider, PhysicalFileProvider>();
            //services.AddScoped<IUnitOfWork, DapperUnitOfWork>();
            services.AddScoped <ICategoryService, CategoryService>();

            services
            .AddMvcCore()
            .AddJsonFormatters()
            .AddJsonOptions(option =>
            {
                option.SerializerSettings.ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                };
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services
            .AddApiVersioning(options =>
            {
                options.ApiVersionReader = new MediaTypeApiVersionReader();
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
                options.ReportApiVersions  = true;
            })
            .AddVersionedApiExplorer(options => { options.GroupNameFormat = "'v'VVV"; });

            services.AddMvc();

            //services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            ////.AddJwtBearer(o =>
            ////{
            ////    o.Authority = "http://localhost:5000";
            ////    o.Audience = "audiobooks";
            ////    o.RequireHttpsMetadata = false;
            ////});
            //.AddIdentityServerAuthentication(options =>
            //{
            //    options.Authority = authenticationCfg.Authority;
            //    options.ApiName = authenticationCfg.Audience;
            //    options.RequireHttpsMetadata = false;
            //    options.SaveToken = true;
            //});

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(
                options =>
            {
                var provider = services.BuildServiceProvider().GetRequiredService <IApiVersionDescriptionProvider>();

                foreach (var description in provider.ApiVersionDescriptions)
                {
                    options.SwaggerDoc(
                        description.GroupName,
                        new Info()
                    {
                        Title   = $"AudioBook API {description.ApiVersion}",
                        Version = description.ApiVersion.ToString()
                    });
                }

                options.AddSecurityDefinition("Bearer", new ApiKeyScheme()
                {
                    Name = "Authorization",
                    In   = "header"
                });

                //options.OperationFilter<AuthorizationHeaderOperationFilter>();
                options.DocumentFilter <SwaggerSecurityRequirementsDocumentFilter>();
            });
        }
Esempio n. 2
0
 public UserRepository(AppConnections appConnection) : base(appConnection.DbContext)
 {
     this._connectionString = appConnection.DbContext;
 }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddOptions();

            // Add Cors service.
            services.AddCors(options =>
            {
                options
                .AddPolicy("CorsPolicy", p => p
                           .AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader()
                           );
            });

            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
            services.AddRouting(options => options.LowercaseUrls  = true);

            services.Configure <AppSettings>(Configuration.GetSection("AppSettings"));
            services.Configure <AppConnections>(Configuration.GetSection("ConnectionStrings"));

            services.AddSingleton <IConfiguration>(Configuration);

            var appSettings = new AppSettings();

            Configuration.Bind("AppSettings", appSettings);
            services.AddSingleton <AppSettings>(appSettings);

            var appConnections = new AppConnections();

            Configuration.Bind("ConnectionStrings", appConnections);
            services.AddSingleton <AppConnections>(appConnections);

            var authenticationCfg = new AuthenticationCfg();

            Configuration.Bind("Authentication", authenticationCfg);
            services.AddSingleton <AuthenticationCfg>(authenticationCfg);

            services.AddHttpContextAccessor();
            services.AddTransient <ClaimsPrincipal>(x =>
            {
                IHttpContextAccessor currentContext = x.GetService <IHttpContextAccessor>();
                return(currentContext.HttpContext.User);
            });

            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IAuthorRepository, AuthorRepository>();
            services.AddScoped <ICategoryRepository, CategoryRepository>();
            services.AddScoped <IAudioBookRepository, AudioBookRepository>();
            services.AddScoped <IAudioBookTrackRepository, AudioBookTrackRepository>();
            services.AddScoped <IBookReaderRepository, BookReaderRepository>();

            // Mediator
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(CommonPipelineBehavior <,>));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>));
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(RequestPostProcessorBehavior <,>));
            System.Reflection.Assembly assembly = AppDomain.CurrentDomain.Load("AudioBook.Api");
            services.AddMediatR(assembly);

            services
            .AddControllers(options =>
            {
                options.RespectBrowserAcceptHeader = true;     // false by default
            })
            .AddJsonOptions(options =>
            {
                // Use the default property (Pascal) casing.
                options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                options.JsonSerializerOptions.AllowTrailingCommas  = true;
                //options.JsonSerializerOptions.IgnoreNullValues = true;
                // Configure a custom converter.
                //options.SerializerOptions.Converters.Add(new MyCustomJsonConverter());
            })
            //.AddJsonFormatters()
            //.AddJsonOptions(option =>
            //{
            //    option.SerializerSettings.ContractResolver = new DefaultContractResolver
            //    {
            //        NamingStrategy = new SnakeCaseNamingStrategy()
            //    };
            //})
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddFluentValidation(option =>
            {
                option.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
                option.RegisterValidatorsFromAssembly(assembly);
            });

            // Customise default API behaviour
            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.SuppressConsumesConstraintForFormFileParameters = true;
                options.SuppressInferBindingSourcesForParameters        = true;
                options.SuppressModelStateInvalidFilter = true;
                options.SuppressMapClientErrors         = true;
                options.ClientErrorMapping[404].Link    =
                    "https://httpstatuses.com/404";
            });

            services
            .AddApiVersioning(options =>
            {
                options.ApiVersionReader = new MediaTypeApiVersionReader();
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
                options.ReportApiVersions  = true;
            })
            .AddVersionedApiExplorer(options =>
            {
                // add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
                // note: the specified format code will format the version as "'v'major[.minor][-status]"
                options.GroupNameFormat = "'v'VVV";

                // note: this option is only necessary when versioning by url segment. the SubstitutionFormat
                // can also be used to control the format of the API version in route templates
                options.SubstituteApiVersionInUrl = true;
            });

            //services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            ////.AddJwtBearer(o =>
            ////{
            ////    o.Authority = "http://localhost:5000";
            ////    o.Audience = "audiobooks";
            ////    o.RequireHttpsMetadata = false;
            ////});
            //.AddIdentityServerAuthentication(options =>
            //{
            //    options.Authority = authenticationCfg.Authority;
            //    options.ApiName = authenticationCfg.Audience;
            //    options.RequireHttpsMetadata = false;
            //    options.SaveToken = true;
            //});

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddTransient <IConfigureOptions <SwaggerGenOptions>, ConfigureSwaggerOptions>();
            services.AddSwaggerGen(
                options =>
            {
                // add a custom operation filter which sets default values
                options.OperationFilter <SwaggerDefaultValues>();
            });
        }
Esempio n. 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add Cors service.
            services.AddCors(options => options
                             .AddPolicy("CorsPolicy", p => p
                                        .AllowAnyOrigin()
                                        .AllowAnyMethod()
                                        .AllowAnyHeader()
                                        )
                             );

            // XSRF
            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

            services.Configure <AppConnections>(Configuration.GetSection("ConnectionStrings"));
            var appConnections = new AppConnections();

            Configuration.Bind("ConnectionStrings", appConnections);
            services.AddSingleton <AppConnections>(appConnections);

            services.AddSingleton <IConfiguration>(Configuration);

            // Repository
            services.AddScoped <IFileRepository, FileRepository>();

            // Service
            services.AddScoped <IFileService, FileService>();

            services
            .AddMvcCore()
            .AddJsonFormatters()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services
            .AddApiVersioning(options =>
            {
                options.ApiVersionReader = new MediaTypeApiVersionReader();
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options);
                options.ReportApiVersions  = true;
            })
            .AddVersionedApiExplorer(options => { options.GroupNameFormat = "'v'VVV"; });

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(
                options =>
            {
                var provider = services.BuildServiceProvider().GetRequiredService <IApiVersionDescriptionProvider>();

                foreach (var description in provider.ApiVersionDescriptions)
                {
                    options.SwaggerDoc(
                        description.GroupName,
                        new Info()
                    {
                        Title   = $"File API {description.ApiVersion}",
                        Version = description.ApiVersion.ToString()
                    });
                }

                options.AddSecurityDefinition("Bearer", new ApiKeyScheme()
                {
                    Name = "Authorization",
                    In   = "header"
                });

                //options.OperationFilter<AuthorizationHeaderOperationFilter>();
                options.DocumentFilter <SwaggerSecurityRequirementsDocumentFilter>();
            });
        }
Esempio n. 5
0
 public AudioBookTrackRepository(AppConnections appConnection) : base(appConnection.DbContext)
 {
     this._connectionString = appConnection.DbContext;
 }