using Infrastructure.Data; using Infrastructure.Jwt; using Infrastructure.Office; using Infrastructure.Security; using Infrastructure.UI; using Infrastructure.Web.Authentication.Cookies; using Infrastructure.Web.Mvc.ModelBinding.Metadata; using Infrastructure.Web.SignalR; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json.Serialization; using Swashbuckle.AspNetCore.Swagger; using System; using System.Globalization; using System.Reflection; using System.Text.Encodings.Web; using System.Text.Unicode; using System.Threading.Tasks; namespace Infrastructure.Web { public class BaseStartup { protected readonly IConfiguration _cfg; protected readonly IHostingEnvironment _env; private readonly bool _useMiniProfiler; protected string connectionString; protected bool useSqlite; public BaseStartup(IConfiguration configuration, IHostingEnvironment env) { this._cfg = configuration; this._env = env; this._useMiniProfiler = this._cfg.GetValue("UseMiniProfiler", false); } public virtual void ConfigureServices(IServiceCollection services) { services.AddSingleton(_cfg as IConfigurationRoot); if (this._useMiniProfiler) { services.AddMiniProfiler().AddEntityFramework(); } services.AddCors(options => options.AddPolicy("CorsPolicy", builder => { builder.SetIsOriginAllowed(o => true) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); })); services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All)); services.Configure(o => { o.ValueCountLimit = int.MaxValue; o.MultipartBodyLengthLimit = long.MaxValue; }); this.ConfigureOptions(services); EfDbContext.OnModelCreatingAction = this.OnModelCreating; services.AddScoped(); this.useSqlite = this._cfg.GetSection("AppSettings").GetValue("database") == "sqlite"; if (useSqlite) { connectionString = this._cfg.GetConnectionString("database.sqlite.connection"); services.AddDbContext(options => options.UseSqlite(connectionString)); } else { connectionString = this._cfg.GetConnectionString("database.mysql.connection"); services.AddDbContext(options => options.UseMySql(connectionString)); } //https://github.com/aspnet/Entropy/blob/master/samples/Localization.StarterWeb/Startup.cs services.AddLocalization(options => options.ResourcesPath = null); //https://yetawf.com/BlogEntry/Title/AdditionalMetadataAttribute%20Anyone/?BlogEntry=1005 services.AddMvc(o => o.ModelMetadataDetailsProviders.Add(new AdditionalMetadataProvider())) .SetCompatibilityVersion(CompatibilityVersion.Latest) .AddJsonOptions(o => { o.SerializerSettings.ContractResolver = new DefaultContractResolver(); }) .AddControllersAsServices() .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => { var localizer = factory.Create("Resources.Resource", Assembly.GetEntryAssembly().FullName); return localizer; }; }); services.Configure(o => { var supportedCultures = new[] { new CultureInfo("zh-CN"), new CultureInfo("en-US") }; o.DefaultRequestCulture = new RequestCulture(culture: "zh-CN", uiCulture: "zh-CN"); o.SupportedCultures = supportedCultures; o.SupportedUICultures = supportedCultures; }); this.AddAuthentication(services); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = this._cfg.GetValue("openapi.title", "web api"), Version = this._cfg.GetValue("openapi.version", "1.0") }); c.EnableAnnotations(); }); services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.HttpOnly = true; }); services.AddHttpClient(); services.AddSignalR(o => o.EnableDetailedErrors = true) .AddJsonProtocol(options => { options.PayloadSerializerSettings.ContractResolver = new DefaultContractResolver(); }); ; services.AddMemoryCache(); services.AddHttpContextAccessor(); services.AddSingleton(); services.AddTransient(typeof(IRepository<>), typeof(EfRepository<>)); services.AddTransient(); services.AddTransient(); services.AddTransient(); } public virtual void ConfigureOptions(IServiceCollection services) { services.ConfigureOptions(new FileConfigureOptions(this._env)); } public virtual void AddAuthentication(IServiceCollection services) { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, opts => { opts.Cookie.Name = this.GetType().FullName; opts.LoginPath = "/Account/Login"; opts.LogoutPath = "/Account/Logout"; opts.AccessDeniedPath = "/Account/AccessDenied"; //不配置SessionStore则存储到cookie var useCookieSessionStore = this._cfg.GetSection("AppSettings").GetValue("UseCookieSessionStore"); if (!useCookieSessionStore) { opts.SessionStore = services.BuildServiceProvider().GetService(); } opts.Events = new CookieAuthenticationEvents { //OnRedirectToLogin = RedirectToLogin(), OnValidatePrincipal = ValidatePrincipal }; }); } public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseStatusCodePagesWithReExecute("/Error"); } if (this._useMiniProfiler) { app.UseMiniProfiler(); } app.UseStaticFiles(); var localizationOption = app.ApplicationServices.GetService>(); app.UseRequestLocalization(localizationOption.Value); app.UseSession(); this.UseAuthentication(app); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1"); }); app.UseCors("CorsPolicy"); this.UseSignalR(app); app.UseMvc(routes => { routes.MapRoute( name: "areas", template: "{area:exists}/{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); }); using (var scope = app.ApplicationServices.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetService(); var configuration = services.GetService(); if (context.Database.EnsureCreated()) { this.Seed(context, services, configuration); } } } public virtual void UseAuthentication(IApplicationBuilder app) { app.UseAuthentication(); } public virtual void UseSignalR(IApplicationBuilder app) { app.UseSignalR(routes => { routes.MapHub("/hub", o => { o.ApplicationMaxBufferSize = long.MaxValue; o.TransportMaxBufferSize = long.MaxValue; }); }); } public virtual void OnModelCreating(ModelBuilder modelBuilder) { } public virtual void Seed(DbContext dbContext, IServiceProvider serviceProvider, IConfiguration configuration) { } public virtual Task ValidatePrincipal(CookieValidatePrincipalContext arg) { return Task.CompletedTask; } } }