Beispiel #1
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            // seed: https://dotnetthoughts.net/seed-database-in-aspnet-core/s
            using (var scope = host.Services.CreateScope())
            {
                var services    = scope.ServiceProvider;
                var context     = services.GetRequiredService <ApplicationDbContext>();
                var userManager = services.GetRequiredService <UserManager <ApplicationUser> >();
                var roleManager = services.GetRequiredService <RoleManager <ApplicationRole> >();
                var seedConfig  = services.GetRequiredService <IOptions <SeedConfiguration> >();
                try
                {
                    await context.Database.MigrateAsync();

                    await DbSeeder.SeedAsync(context, userManager, roleManager, seedConfig);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "An error occurred seeding the DB");
                    throw;
                }
            }

            await host.RunAsync();
        }
Beispiel #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            // Configure a rewrite rule to auto-lookup for standard default filessuch as index.html.
            app.UseDefaultFiles();
            // Serve static files (html, css, js, images & more). See also the following URL:
            // https://docs.asp.net/en/latest/fundamentals/static-files.html for further reference.
            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = (context) =>
                {
                    // Disable caching for all static files.
                    context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
                    context.Context.Response.Headers["Pragma"]        = Configuration["StaticFiles:Headers:Pragma"];
                    context.Context.Response.Headers["Expires"]       = Configuration["StaticFiles:Headers:Expires"];
                }
            });

            // Add a custom Jwt Provider to generate Tokens
            app.UseJwtProvider();

            // Add the Jwt Bearer Header Authentication to validate Tokens
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                RequireHttpsMetadata      = false,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey         = JwtProvider.SecurityKey,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = JwtProvider.Issuer,
                    ValidateIssuer   = false,
                    ValidateAudience = false
                }
            });

            // app.UseApplicationInsightsRequestTelemetry();

            // app.UseApplicationInsightsExceptionTelemetry();

            // Add MVC to the pipeline
            app.UseMvc();

            // TinyMapper binding configuration
            TinyMapper.Bind <Item,
                             ItemViewModel>();

            // Seed the Database (if needed)
            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (AggregateException e)
            {
                throw new Exception(e.ToString());
            }
        }
Beispiel #3
0
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var serviceScope = host.Services.CreateScope())
            {
                var loggerFactory = serviceScope.ServiceProvider.GetRequiredService <ILoggerFactory>();

                try
                {
                    var context = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();
                    context.Database.Migrate();

                    var config = serviceScope.ServiceProvider.GetRequiredService <IConfiguration>();

                    DbSeeder dbSeeder = new DbSeeder(loggerFactory, config);
                    dbSeeder.SeedAsync(serviceScope.ServiceProvider,
                                       serviceScope.ServiceProvider.GetService <UserManager <ApplicationUser> >(),
                                       serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> >(),
                                       CancellationToken.None).GetAwaiter().GetResult();
                }
                catch (Exception ex)
                {
                    var logger = loggerFactory.CreateLogger("Program");
                    logger.LogError(ex, "database migration failed. Please verify your connection string and database are correctly setup.");
                }
            }

            host.Run();
        }
Beispiel #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, DbSeeder dbSeeder)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetService <DatabaseContext>();

                dbContext.Database.Migrate();

                dbSeeder.SeedAsync().Wait();
            }
        }
Beispiel #5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseDefaultFiles();

            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context =>
                {
                    // Disable caching for all static files.
                    context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
                    context.Context.Response.Headers["Pragma"]        = Configuration["StaticFiles:Headers:Pragma"];
                    context.Context.Response.Headers["Expires"]       = Configuration["StaticFiles:Headers:Expires"];
                }
            });

            app.UseMvc();

            // Seed the Database (if needed)
            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (AggregateException e)
            {
                throw new Exception(e.ToString());
            }
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
        {
#pragma warning disable CS0618 // Type or member is obsolete
            loggerFactory.AddConsole(configuration: Configuration.GetSection("Loading"));
#pragma warning restore CS0618 // Type or member is obsolete
#pragma warning disable CS0618 // Type or member is obsolete
            loggerFactory.AddDebug();
#pragma warning restore CS0618 // Type or member is obsolete
            dbSeeder.SeedAsync().Wait();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseCors(
                options => options.WithOrigins("http://localhost:3000").AllowAnyHeader()
                );
            app.UseMvc();
        }
Beispiel #7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, DbSeeder dbseeder)
        {
            app.UseCors(builder =>
            {
                builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin();
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseMvc();

            //handle client side orutes
            //https://weblog.west-wind.com/posts/2017/Aug/07/Handling-HTML5-Client-Route-Fallbacks-in-ASPNET-Core
            app.Run(async(context) =>
            {
                context.Response.ContentType = "text/html";
                await context.Response.SendFileAsync(Path.Combine(env.WebRootPath, "index.html"));
            });

            dbseeder.SeedAsync(app.ApplicationServices).Wait();
        }
Beispiel #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, DbSeeder dbseeder)
        {
            app.UseCors("CorsPolicy");
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseSignalR(routes =>
            {
                routes.MapHub <CoffeeHub>("/coffeeHub");
            });

            app.UseAuthentication();
            app.UseMvc();

            dbseeder.SeedAsync(app.ApplicationServices).Wait();
        }
Beispiel #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, DbSeeder dbseeder)
        {
            app.UseCors(builder =>
            {
                builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin();
            });

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseMvc();

            dbseeder.SeedAsync(app.ApplicationServices).Wait();
        }
Beispiel #10
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
        {
            app.UseDeveloperExceptionPage();

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            dbSeeder.SeedAsync().Wait();
            app.UseMvc();
        }
Beispiel #11
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context =>
                {
                    // Disable caching for all static files.
                    context.Context.Response.Headers["Cache-Control"] =
                        Configuration["StaticFiles:Headers:Cache-Control"];
                    context.Context.Response.Headers["Pragma"] =
                        Configuration["StaticFiles:Headers:Pragma"];
                    context.Context.Response.Headers["Expires"] =
                        Configuration["StaticFiles:Headers:Expires"];
                }
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Ang}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <Item, ItemViewModel>();
                cfg.CreateMap <ItemViewModel, Item>();
            });
            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (AggregateException e)
            {
                throw new Exception(e.ToString());
            }
        }
Beispiel #12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                // Need to understand why Migrations fail when this line is here.
                DbSeeder.SeedAsync(app.ApplicationServices).Wait();
            }

            app.UseMvc();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
        {
            //bu metodlda requestlerin nasıl karşılanacağına dair yazılan kodlardır.
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            //loglamanın nasıl yapılacağını bildirir
            loggerFactory.AddDebug();
            //hem console hem de debug klasörüneloglama yapılması gerektiği yazılmış
            dbSeeder.SeedAsync().Wait();
            app.UseMvc();

            //yüklenmiş olan paketler .csproj dosyasına kaydedilir odosyaya ise projeye sağ tık yapıp edi derseniz gidebilirsiniz
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              ILoggerFactory loggerFactory, DbSeeder seeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            var options = new RewriteOptions()
                          .AddIISUrlRewrite(env.ContentRootFileProvider, "IISUrlRewrite.xml");

            app.UseRewriter(options);

            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context => {
                    context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
                    context.Context.Response.Headers["Pragma"]        = Configuration["StaticFiles:Headers:Pragma"];
                    context.Context.Response.Headers["Expires"]       = Configuration["StaticFiles:Headers:Expires"];
                }
            });

            // Add a custom Jwt Provider to generate Tokens
            // app.UseJwtProvider();
            // Add the Jwt Bearer Header Authentication to validate Tokens
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                Authority                 = "http://localhost:5000/",
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                RequireHttpsMetadata      = false,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    // IssuerSigningKey = JwtTokenProvider.SecurityKey,
                    // ValidateIssuerSigningKey = true,
                    // ValidIssuer = JwtTokenProvider.Issuer,
                    ValidateIssuer   = false,
                    ValidateAudience = false
                }
            });

            app.UseOpenIddict();

            app.UseMvc();

            try
            {
                seeder.SeedAsync().Wait();
            }
            catch (AggregateException e)
            {
                throw new Exception(e.ToString());
            }
        }
Beispiel #15
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, DbSeeder dbSeeder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            /*app.UseCors(builder =>
             * builder.WithOrigins("https://localhost:44394/").AllowAnyMethod()
             *
             * );*/

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            // Seed the Database (if needed)
            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (System.AggregateException e)
            {
                throw new Exception(e.ToString());
            }


            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
        private async Task RunSeedInNewScopeAsync()
        {
            // new scope to reset EF cache
            using (var scope = _scopeFactory.CreateScope())
            {
                var applicationDbContext = scope.ServiceProvider.GetService <ApplicationDbContext>();
                var userMgr      = scope.ServiceProvider.GetService <UserManager <ApplicationUser> >();
                var roleMgr      = scope.ServiceProvider.GetService <RoleManager <ApplicationRole> >();
                var seedSettings = scope.ServiceProvider.GetService <IOptions <SeedConfiguration> >();

                await _context.Database.MigrateAsync();

                await DbSeeder.SeedAsync(applicationDbContext, userMgr, roleMgr, seedSettings);
            }
        }
Beispiel #17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();
            app.UseSpaStaticFiles();
            app.UseAuthentication();

            app.UseStatusCodePagesWithReExecute("/error/{0}");

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });


            using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                var dbContext   = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();
                var userManager = serviceScope.ServiceProvider.GetService <UserManager <ApplicationUser> >();
                var roleManager = serviceScope.ServiceProvider.GetService <RoleManager <IdentityRole> >();
                dbContext.Database.Migrate();
                DbSeeder.SeedAsync(dbContext, userManager, roleManager).GetAwaiter().GetResult();
            }
        }
Beispiel #18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                              ILoggerFactory loggerFactory, DbSeeder dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
                    HotModuleReplacement = true
                });
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });

            //AutoMapper binding configuration
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <Item, ItemViewModel>();
            });
            //Seeed the Database (if needed)
            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (AggregateException e)
            {
                throw new Exception(e.ToString());
            }
        }
Beispiel #19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseDefaultFiles();
            app.UseStaticFiles();

            //add our JwtProvider that we created
            app.UseJwtProvider();

            //add the built in authentication
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                RequireHttpsMetadata      = false,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey         = JwtProvider.SecurityKey,
                    ValidIssuer              = JwtProvider.Issuer,
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                }
            }


                                           );

            //if we wanted to support cookies, we do this:
            //app.UseIdentity();
            //or this
            //app.UseCookieAuthentication();

            app.UseMvc();

            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (AggregateException e)
            {
                throw new Exception(e.ToString());
            }
        }
Beispiel #20
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseDefaultFiles();
            app.UseStaticFiles();

            app.UseMvc();

            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (AggregateException ex)
            {
                throw new Exception(ex.ToString());
            }
        }
Beispiel #21
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              ILoggerFactory loggerFactory,
                              DbSeeder dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseIdentity();

            app.UseCors("EnableCORS");

            // Add a custom Jwt Provider to generate Tokens
            app.UseJwtProvider();

            // Add the Jwt Bearer Header Authentication to validate Tokens
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                RequireHttpsMetadata      = false,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey         = JwtProvider.SecurityKey,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = JwtProvider.Issuer,
                    ValidateIssuer   = false,
                    ValidateAudience = false
                }
            });

            // Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715
            app.UseMvc();

            // Seed the Database (if needed)
            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (AggregateException e)
            {
                throw new Exception(e.ToString());
            }
        }
Beispiel #22
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder, UserManager <ApplicationUser> userManager, TokenHelper tokenHelper, APIDbContext db)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("any");
            //在当前路径中开启默认文件映射
            app.UseDefaultFiles();
            //启用给定选项的静态文件服务。
            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = (context) =>
                {
                    context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
                    context.Context.Response.Headers["Pragma"]        =
                        Configuration["StaticFiles:Headers:Pragma"];
                    context.Context.Response.Headers["Expires"] =
                        Configuration["StaticFiles:Headers:Expires"];
                }
            });

            //将中间件添加到请求管道中
            app.UseJWTMiddleware();
            app.UseAuthentication();
            app.UseMvc();

            ////生成数据库执行此方法
            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            //在应用程序执行期间响应一个或多个错误
            catch (AggregateException e)
            {
                throw new Exception(e.InnerException.ToString());
            }
        }
Beispiel #23
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope()) {
                var services = scope.ServiceProvider;
                try {
                    var context     = services.GetRequiredService <Persistence.DataContext>();
                    var userManager = services.GetRequiredService <UserManager <AppUser> >();
                    await context.Database.MigrateAsync();

                    await DbSeeder.SeedAsync(context, userManager);
                } catch (Exception ex) {
                    var logger = services.GetRequiredService <ILogger <Program> >();
                    logger.LogError(ex, "Error occured during MeetUppy db migration.");
                }
            };

            host.Run();
        }
Beispiel #24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              ILoggerFactory loggerFactory,
                              DbSeeder dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            // Configure a rewrite rule to auto-lookup for standard default files
            // such as index.html.
            app.UseDefaultFiles();

            // Serve static files (html, css, js, images & more).
            //See also the following URL:
            // https://docs.asp.net/en/latest/fundamentals/static-files.html
            //for further reference.
            app.UseStaticFiles(
                new StaticFileOptions()
            {
                OnPrepareResponse = (context) =>
                {
                    // Disable caching for all static files.
                    context.Context.Response.Headers["Cache-Control"] =
                        Configuration["StaticFiles:Headers:Cache-Control"];
                    context.Context.Response.Headers["Pragma"] =
                        Configuration["StaticFiles:Headers:Pragma"];
                    context.Context.Response.Headers["Expires"] =
                        Configuration["StaticFiles:Headers:Expires"];
                }
            });
            app.UseMvc();
            // Seed the Database (if needed)
            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (AggregateException e)
            {
                throw new Exception(e.ToString());
            }
        }
Beispiel #25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, DbSeeder dbSeeder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseAuthentication();

            app.UseMvc();

            app.UseSwagger();
            app.UseSwaggerUI(options => options.SwaggerEndpoint("/swagger/v2/swagger.json", "Parkrun API"));
            dbSeeder.SeedAsync().Wait();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
                              DbSeeder dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseDeveloperExceptionPage();

            //app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            dbSeeder.SeedAsync(app.ApplicationServices).Wait();
        }
Beispiel #27
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            using (var scope = host.Services.CreateScope())
            {
                var services      = scope.ServiceProvider;
                var loggerFactory = services.GetRequiredService <ILoggerFactory>();
                try
                {
                    var context = services.GetRequiredService <ApplicationDbContext>();
                    await context.Database.MigrateAsync();

                    await DbSeeder.SeedAsync(context, loggerFactory);
                }
                catch (Exception ex)
                {
                    var logger = loggerFactory.CreateLogger <Program>();
                    logger.LogError(ex, "and error occurred during migration");
                }
            }

            host.Run();
        }
Beispiel #28
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = context =>
                {
                    //Disable Caching for Static Files
                    context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
                    context.Context.Response.Headers["Pragma"]        = Configuration["StaticFiles:Headers:Pragma"];
                    context.Context.Response.Headers["Expires"]       = Configuration["StaticFiles:Headers:Expires"];
                }
            });

            // Add a custom Jwt Provider to generate Tokens
            app.UseJwtProvider();


            app.UseIdentity();

            // Add external authentication middleware below.
            // To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
            app.UseFacebookAuthentication(new FacebookOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                AppId        = Configuration["Authentication:Facebook:AppId"],
                AppSecret    = Configuration["Authentication:Facebook:AppSecret"],
                CallbackPath = "/signin-facebook",
                Scope        = { "email" }
            });

            app.UseGoogleAuthentication(new GoogleOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                ClientId     = Configuration["Authentication:Google:ClientId"],
                ClientSecret = Configuration["Authentication:Google:ClientSecret"],
                CallbackPath = "/signin-google",
                Scope        = { "email" }
            });

            app.UseTwitterAuthentication(new TwitterOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                ConsumerKey           = Configuration["Authentication:Twitter:ConsumerKey"],
                ConsumerSecret        = Configuration["Authentication:Twitter:ConsumerSecret"],
                CallbackPath          = "/signin-twitter"
            });

            app.UseOpenIddict();

            // Add the Jwt Bearer Header Authentication to validate Tokens
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                RequireHttpsMetadata      = false,
                Authority                 = Configuration["Authentication:OpenIddict:Authority"],
                TokenValidationParameters = new TokenValidationParameters()
                {
                    //IssuerSigningKey = JwtProvider.SecurityKey,
                    //ValidateIssuerSigningKey = true,
                    //ValidIssuer = JwtProvider.Issuer,
                    ValidateIssuer   = false,
                    ValidateAudience = false
                }
            });

            // Add MVC to the pipeline
            app.UseMvc();

            //Tiny Maper binding config
            TinyMapper.Bind <Item, ItemViewModel>();

            // Seed the DB if needed
            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (AggregateException e)
            {
                throw new Exception(e.ToString());
            }
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            DbSeeder dbSeeder)
        {
            app.Use(async(context, next) =>
            {
                await next();

                if (context.Response.StatusCode == 404 &&
                    !Path.HasExtension(context.Request.Path.Value))
                {
                    context.Request.Path = "/index.html";
                    await next();
                }
            });

            app.UseDefaultFiles();
            app.UseStaticFiles();

            // Add a cutom JWT provide to generate tokens
            app.UseJwtProvider();
            // Add the JWT Bearer Header Authentication to validate Tokens
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = false,
                RequireHttpsMetadata      = false,
                TokenValidationParameters = new TokenValidationParameters
                {
                    IssuerSigningKey         = JwtProvider.SecurityKey,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = JwtProvider.Issuer,
                    ValidateIssuer   = false,
                    ValidateAudience = false
                }
            });

            app.UseIdentity();

            app.UseMvc(routes =>
            {
                // Routes sample A
                routes.MapRoute(
                    name: "RouteSampleA",
                    template: "MyOwnGet",
                    defaults: new
                {
                    controller = "Items",
                    action     = "Get"
                }
                    );

                // Route sample B
                routes.MapRoute(
                    name: "RouteSampleB",
                    template: "MyOwnPost",
                    defaults: new
                {
                    controller = "Items",
                    action     = "Post"
                }
                    );
            });

            // TinyMapper binding configuration
            TinyMapper.Bind <Item, ItemViewModel>();

            // Seed the Database (if needed)
            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }
Beispiel #30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DbSeeder dbSeeder)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            // Configure a rewrite rule to auto-lookup for standard default files such as index.html.
            app.UseDefaultFiles();

            // Serve static files (html, css, js, images & more). See also the following URL:
            // https://docs.asp.net/en/latest/fundamentals/static-files.html for further reference.
            app.UseStaticFiles(new StaticFileOptions()
            {
                OnPrepareResponse = (context) =>
                {
                    // Disable caching for all static files.
                    context.Context.Response.Headers["Cache-Control"] = Configuration["StaticFiles:Headers:Cache-Control"];
                    context.Context.Response.Headers["Pragma"]        = Configuration["StaticFiles:Headers:Pragma"];
                    context.Context.Response.Headers["Expires"]       = Configuration["StaticFiles:Headers:Expires"];
                }
            });

            // Add a custom Jwt Provider to generate Tokens
            app.UseJwtProvider();

            // Add the AspNetCore.Identity middleware (required for external auth providers)
            // IMPORTANT:: This must be placed *BEFORE* OpenIddict and any external provider's middleware.
            app.UseIdentity();

            // Add external authentication middleware below
            // To configure them please se: http://go.microsoft.com/fwlink/?LinkID=532715
            app.UseFacebookAuthentication(new FacebookOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                AppId        = Configuration["Authentication:Facebook:AppId"],
                AppSecret    = Configuration["Authentication:Facebook:AppSecret"],
                CallbackPath = "/signin-facebook",
                Scope        = { "email" }
            });

            app.UseGoogleAuthentication(new GoogleOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                ClientId     = Configuration["Authentication:Google:ClientId"],
                ClientSecret = Configuration["Authentication:Google:ClientSecret"],
                CallbackPath = "/signin-google",
                Scope        = { "email " }
            });

            // Add the Jwt Bearer Header Authentication to validate Tokens
            app.UseJwtBearerAuthentication(new JwtBearerOptions()
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                RequireHttpsMetadata      = false,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey         = JwtProvider.SecurityKey,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = JwtProvider.Issuer,
                    ValidateIssuer   = false,
                    ValidateAudience = false
                }
            });

            // Add MVC to the pipeline
            app.UseMvc();

            // TinyMapper build configuration
            TinyMapper.Bind <Item, ItemViewModel>();

            // Seed the Database (if needed)
            try
            {
                dbSeeder.SeedAsync().Wait();
            }
            catch (AggregateException e)
            {
                throw new Exception(e.ToString());
            }
        }