代码拉取完成,页面将自动刷新
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using MVC.CustomerMiddlewares;
using MVC.Repository;
using MVC.Repository.Interface;
using Microsoft.AspNetCore.Http;
using MVC.Common;
using MVC.Security;
namespace MVC
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
#region 添加数据库连接池
services.AddDbContextPool<AppDBContext>(option => {
option.UseSqlServer(Configuration.GetConnectionString("AppDB"));
});
#endregion
#region 注入业务
services.AddTransient<IStudentRepository, StudentRepository>();
services.AddTransient(typeof(IRepository<,>),typeof(RepositoryBase<,>));
#endregion
#region 添加Identity服务
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddErrorDescriber<CustomIdentityErrorDescriber>()
.AddEntityFrameworkStores<AppDBContext>();
services.Configure<IdentityOptions>(options =>
{
//密码中允许最大的重复字符数
options.Password.RequiredUniqueChars = 3;
//密码必须至少有一个非字母数字的字符
options.Password.RequireNonAlphanumeric = false;
//密码是否必须包含小写字母
options.Password.RequireLowercase = false;
//密码是否必须包含大写字母
options.Password.RequireUppercase = false;
});
#endregion
#region 添加AutoMapper
services.AddAutoMapper(typeof(Startup));
#endregion
services.AddSingleton<DataProtectionPurposeStrings>();
services.AddSingleton<IAuthorizationHandler, CanEditOnlyOtherAdminRolesAndClaimsHandler>();
services.AddSingleton<IAuthorizationHandler, SuperAdminHandler>();
services.ConfigureApplicationCookie(options=> {
//修改拒绝访问的路由地址
options.AccessDeniedPath = new PathString("/Admin/AccessDenied");
//修改登录地址的路由
options.LoginPath = new PathString("/Account/Login");
//修改注销地址的路由
options.LogoutPath = new PathString("/Account/LogOut");
//统一系统全局的Cookie名称
options.Cookie.Name = "MvcCookieName";
//是否对Cookie启用滑动过期时间
options.SlidingExpiration = true;
//登录用户Cookie的有效期
options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
});
services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
{
microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ClientId"];
microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];
})
.AddGitHub(options =>
{
options.ClientId = Configuration["Authentication:GitHub:ClientId"];
options.ClientSecret = Configuration["Authentication:GitHub:ClientSecret"];
});
services.AddAuthorization(options => {
options.AddPolicy("DeleteRolePolicy",
policy => policy.RequireClaim("Delete Role"));
options.AddPolicy("AdminRolePolicy",
policy => policy.RequireRole("Admin"));
//策略结合多个角色进行授权
options.AddPolicy("SuperAdminPolicy",
policy => policy.RequireRole("Admin", "User", "SuperManager"));
options.AddPolicy("EditRolePolicy",
policy => policy.AddRequirements(new ManageAdminRolesAndClaimsRequirement()));
options.InvokeHandlersAfterFailure = false;
});
services.AddControllersWithViews(config =>
{
//全局应用authorize,所有控制器
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
}
private bool AuthorizeAccess(AuthorizationHandlerContext context)
{
return
context.User.IsInRole("Admin") &&
context.User.HasClaim(claim => claim.Type == "Edit Role" && claim.Value == "true")
|| context.User.IsInRole("Super Admin");
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())//开发者模式
{
app.UseDeveloperExceptionPage();
}
else
{
//app.UseStatusCodePages();//404,一个默认处理
//app.UseStatusCodePagesWithRedirects("/Error/{0}");//404,地址栏改变,重定向到指定页
app.UseStatusCodePagesWithReExecute("/Error/{0}");//404,返回一个错误页,地址栏不变
app.UseExceptionHandler("/Error");//处理异常,500类
}
app.UseStaticFiles();
app.UseRouting();
//验证
app.UseAuthentication();
//授权
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Student}/{action=Index}/{id?}");
});
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。