1 Star 1 Fork 0

hyx/NET_Core_MVC

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Startup.cs 6.19 KB
一键复制 编辑 原始数据 按行查看 历史
xhnbzdl 提交于 2021-10-23 22:54 . 添加项目文件。
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?}");
});
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/huang-yuxiang/net_-core_-mvc.git
git@gitee.com:huang-yuxiang/net_-core_-mvc.git
huang-yuxiang
net_-core_-mvc
NET_Core_MVC
master

搜索帮助