You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
238 lines
9.7 KiB
238 lines
9.7 KiB
using Infrastructure.Data;
|
|
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<bool>("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<FormOptions>(o =>
|
|
{
|
|
o.ValueCountLimit = int.MaxValue;
|
|
o.MultipartBodyLengthLimit = long.MaxValue;
|
|
});
|
|
services.ConfigureOptions(new FileConfigureOptions(this._env));
|
|
EfDbContext.OnModelCreatingAction = this.OnModelCreating;
|
|
services.AddScoped<DbContext, EfDbContext>();
|
|
this.useSqlite = this._cfg.GetSection("AppSettings").GetValue<string>("database") == "sqlite";
|
|
if (useSqlite)
|
|
{
|
|
connectionString = this._cfg.GetConnectionString("database.sqlite.connection");
|
|
services.AddDbContext<EfDbContext>(options => options.UseSqlite(connectionString));
|
|
}
|
|
else
|
|
{
|
|
connectionString = this._cfg.GetConnectionString("database.mysql.connection");
|
|
services.AddDbContext<EfDbContext>(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<RequestLocalizationOptions>(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<string>("openapi.title", "web api"),
|
|
Version = this._cfg.GetValue<string>("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<ITicketStore, DistributedCacheTicketStore>();
|
|
services.AddTransient(typeof(IRepository<>), typeof(EfRepository<>));
|
|
services.AddTransient<IEncryptionService, EncryptionService>();
|
|
services.AddTransient<IExcelReader, ExcelReader>();
|
|
}
|
|
|
|
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<bool>("UseCookieSessionStore");
|
|
if (!useCookieSessionStore)
|
|
{
|
|
opts.SessionStore = services.BuildServiceProvider().GetService<ITicketStore>();
|
|
}
|
|
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<IOptions<RequestLocalizationOptions>>();
|
|
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");
|
|
app.UseSignalR(routes =>
|
|
{
|
|
routes.MapHub<PageHub>("/hub", o =>
|
|
{
|
|
o.ApplicationMaxBufferSize = long.MaxValue;
|
|
o.TransportMaxBufferSize = long.MaxValue;
|
|
});
|
|
});
|
|
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<DbContext>();
|
|
var configuration = services.GetService<IConfiguration>();
|
|
if (context.Database.EnsureCreated())
|
|
{
|
|
this.Seed(context, services, configuration);
|
|
}
|
|
}
|
|
}
|
|
|
|
public virtual void UseAuthentication(IApplicationBuilder app)
|
|
{
|
|
app.UseAuthentication();
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
} |