using Infrastructure.Application.Services.Settings; using Infrastructure.Data; using Infrastructure.Extensions; using Infrastructure.Security; using Infrastructure.Web; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; using System; using System.Reflection; using System.Text; using System.Text.Encodings.Web; using System.Text.Unicode; using System.Threading.Tasks; using TeacherExt.Data; namespace TeacherExt { public class Startup { private readonly string _origins = "AllowAllHeaders"; public Startup(IConfiguration configuration, IHostEnvironment hostEnvironment) { Configuration = configuration; HostEnvironment = hostEnvironment; } public IConfiguration Configuration { get; } public IHostEnvironment HostEnvironment { get; } public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(); services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All)); services.AddHttpContextAccessor(); services.AddCors(options => options.AddPolicy(_origins, builder => { builder.SetIsOriginAllowed(o => true) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials(); })); var database = Configuration.GetValue("database"); services.AddTransient(); var connstr = Configuration.GetConnectionString("mariyadb"); services.AddDbContext(o => o.UseMySql(connstr, ServerVersion.AutoDetect(connstr))); services.AddDistributedMemoryCache(); services.AddScoped(); services.AddTransient(typeof(IRepository<>), typeof(EfRepository<>)); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddLocalization(options => options.ResourcesPath = null); services.AddMvc() .AddNewtonsoftJson() .AddControllersAsServices() .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => { var localizer = factory.Create("Resources.Resource", Assembly.GetEntryAssembly().GetName().Name); return localizer; }; }); services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; //options.ClientErrorMapping[404].Link = "https://httpstatuses.com/404"; }) .AddNewtonsoftJson(o => { o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(o => { services.AddSingleton(o); o.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["jwt:key"])), ValidateIssuer = false, ValidIssuer = Configuration["jwt:issuer"], ValidateAudience = false, ValidAudience = Configuration["jwt:audience"] }; o.Events = new JwtBearerEvents { OnTokenValidated = context => { if (context.SecurityToken == null) { context.Fail("token error"); } else if (DateTime.UtcNow > context.SecurityToken.ValidTo) { context.Fail("token time out"); } return Task.CompletedTask; }, OnForbidden = context => { return context.Response.WriteAsync("403 forbidden"); }, OnAuthenticationFailed = context => { return Task.CompletedTask; }, OnChallenge = context => { if (!context.Request.IsAjax()) { context.Response.Redirect(Configuration["Admin:login"] ?? "/Account/Login"); context.HandleResponse(); } return Task.CompletedTask; }, OnMessageReceived = context => { if (!context.Request.IsStatic()) { if (context.Request.Query.ContainsKey("access_token")) { context.Token = context.Request.Query["access_token"]; } else { var jwtCookieName = context.HttpContext.GetJwtCookieName(); if (!context.Request.Headers.ContainsKey("Authorization") && context.Request.Cookies.Keys.Contains(jwtCookieName)) { context.Token = context.Request.Cookies[jwtCookieName]; } } } return Task.CompletedTask; } }; o.SecurityTokenValidators.Clear(); o.SecurityTokenValidators.Insert(0, new JwtTokenValidator(services.BuildServiceProvider())); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseStaticFiles(); app.UseRouting(); app.UseCors(_origins); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); using var scope = app.ApplicationServices.CreateScope(); //var encryptionService = scope.ServiceProvider.GetRequiredService(); //var salt = "111111"; //var password = encryptionService.CreatePasswordHash(salt, salt); //using var db = scope.ServiceProvider.GetRequiredService(); //var set = "Sex2"; //if (!db.Set().AsNoTracking().Any(o => o.Category == set)) //{ // db.Set().Add(new DictionaryItem { Category = set, Detail = "男", Remark = "男", Code = "男", Order = 1 }); // db.Set().Add(new DictionaryItem { Category = set, Detail = "女", Remark = "女", Code = "女", Order = 2 }); // db.SaveChanges(); //} //var teachPeriod = "MainTeachPeriod2";//t_dm_stage //if (!db.Set().AsNoTracking().Any(o => o.Category == teachPeriod)) //{ // db.Set().Add(new DictionaryItem { Category = teachPeriod, Detail = "学前教育", Remark = "学前教育", Code = "学前教育", Order = 1 }); // db.Set().Add(new DictionaryItem { Category = teachPeriod, Detail = "小学", Remark = "小学", Code = "小学", Order = 2 }); // db.Set().Add(new DictionaryItem { Category = teachPeriod, Detail = "普通初中", Remark = "普通初中", Code = "普通初中", Order = 3 }); // db.Set().Add(new DictionaryItem { Category = teachPeriod, Detail = "无", Remark = "无", Code = "无", Order = 4 }); // db.SaveChanges(); //} //var teachSubject = "MainTeachSubject2";//t_dm_subject //if (!db.Set().AsNoTracking().Any(o => o.Category == teachSubject)) //{ // var subjects = new string[] { // "语文", // "数学", // "英语", // "音乐", // "体育", // "美术", // "科学", // "书法", // "信息技术", // "政治", // "历史", // "地理", // "物理", // "化学", // "生物", // "幼教全科", // "心理健康", // "综合实践课", // "无", // }; // for (int i = 0; i < subjects.Length; i++) // { // var item = subjects[i]; // db.Set().Add(new DictionaryItem { Category = teachSubject, Detail = item, Remark = item, Code = item, Order = i + 1 }); // } // db.SaveChanges(); //} } } }