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.
217 lines
9.5 KiB
217 lines
9.5 KiB
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.AspNetCore.Localization;
|
|
using Microsoft.AspNetCore.Mvc.DataAnnotations;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Localization;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using Newtonsoft.Json;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Globalization;
|
|
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<string>("database");
|
|
services.AddTransient<AesHelper>();
|
|
var connstr = Configuration.GetConnectionString("mariyadb");
|
|
services.AddDbContext<TeacherDbContext>(o => o.UseMySql(connstr, ServerVersion.AutoDetect(connstr)));
|
|
|
|
services.AddDistributedMemoryCache();
|
|
services.AddScoped<DbContext, TeacherDbContext>();
|
|
services.AddTransient(typeof(IRepository<>), typeof(EfRepository<>));
|
|
services.AddTransient<IEncryptionService, EncryptionService>();
|
|
services.AddTransient<SettingService>();
|
|
services.AddTransient<ISettingService, CachedSettingService>();
|
|
services.AddTransient<IUserService, UserService>();
|
|
services.AddLocalization(options => options.ResourcesPath = null);
|
|
services.AddSingleton<IValidationAttributeAdapterProvider, LocalizedValidationAttributeAdapterProvider>();
|
|
services.AddSingleton<LocalizedValidationMetadataProvider>();
|
|
services.Configure<RequestLocalizationOptions>(
|
|
options =>
|
|
{
|
|
var supportedCultures = new List<CultureInfo>{
|
|
//new CultureInfo("en-US"),
|
|
new CultureInfo("zh-CN"),
|
|
};
|
|
options.DefaultRequestCulture = new RequestCulture(culture: "zh-CN", uiCulture: "zh-CN");
|
|
options.SupportedCultures = supportedCultures;
|
|
options.SupportedUICultures = supportedCultures;
|
|
options.RequestCultureProviders.Insert(0, new QueryStringRequestCultureProvider());
|
|
});
|
|
services.AddMvc(o => o.ModelMetadataDetailsProviders.Add(
|
|
new LocalizedValidationMetadataProvider(services.BuildServiceProvider().GetRequiredService<IStringLocalizerFactory>()))
|
|
)
|
|
.AddNewtonsoftJson()
|
|
.AddControllersAsServices();
|
|
//.AddMvcLocalization()
|
|
//.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
|
|
//.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)
|
|
{
|
|
string basePath = this.Configuration.GetValue("BasePath", $"/{Assembly.GetEntryAssembly().GetName().Name}");
|
|
app.UsePathBase(basePath);
|
|
app.UseSwagger();
|
|
app.UseSwaggerUI(c =>
|
|
{
|
|
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
|
|
});
|
|
app.UseStaticFiles();
|
|
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
|
|
app.UseRequestLocalization(locOptions.Value);
|
|
app.UseRouting()
|
|
.UseCors(_origins)
|
|
.UseAuthentication()
|
|
.UseAuthorization()
|
|
.UseEndpoints(endpoints =>
|
|
{
|
|
endpoints.MapControllerRoute(
|
|
name: "default",
|
|
pattern: "{controller=Home}/{action=Index}/{id?}");
|
|
});
|
|
/*生成测试数据库*/
|
|
//if(this.HostEnvironment.IsDevelopment())
|
|
//{
|
|
// using var scope = app.ApplicationServices.CreateScope();
|
|
// using var db = scope.ServiceProvider.GetRequiredService<DbContext>();
|
|
// db.Database.EnsureCreated();
|
|
//}
|
|
}
|
|
}
|
|
} |