asp.net core 2最簡單的登錄功能 源代碼在此 創建asp.net core Web Mvc項目 配置下選項 項目目錄結構 在Models文件夾下新建兩個實體類 在項目文件夾下新建Data文件夾,新建DbContext類 在Startup.cs文件中的ConfigureServices下添 ...
asp.net core 2最簡單的登錄功能
創建asp.net core Web Mvc項目
配置下選項
項目目錄結構
在Models文件夾下新建兩個實體類
public class Test { public int Id { get; set; } [Required] [Display(Name = "某人")] public string Someone { get; set; } [Required] [Display(Name = "某事")] public string Something { get; set; } }
public class User { public int Id { get; set; } [Required] [Display(Name = "用戶名")] public string UserName { get; set; } [Display(Name = "密碼")] [Required] public string UserPwd { get; set; } public string Nothing { get; set; } }
在項目文件夾下新建Data文件夾,新建DbContext類
public class MyDbContext:DbContext { public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { } public DbSet<User> Users { get; set; } public DbSet<Test> Tests { get; set; } }
在Startup.cs文件中的ConfigureServices下添加dbcontext服務
public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); //sqlserver services.AddDbContext<MyDbContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
在appsettings.json下配置資料庫連接字元串
打開程式包管理器控制台,執行生成資料庫上下文和創建更新資料庫命令
去資料庫查看下表是否生成,並直接添加一個種子數據。
添加控制器和視圖
生成之後的項目結構目錄如下
在homecontroller中編寫一個Login方法
public class HomeController : Controller { private readonly MyDbContext _context; public HomeController(MyDbContext context) { _context = context; } public IActionResult Index() { return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } [HttpPost] public async Task<IActionResult> Login(User user) { var loginuser = await _context.Users.FirstOrDefaultAsync(u => u.UserName == user.UserName); if (loginuser == null) return BadRequest("沒有該用戶"); if (loginuser.UserPwd != user.UserPwd) return BadRequest("密碼錯誤"); //聲明對象創建 var claims = new List<Claim> { new Claim(ClaimTypes.Name, user.UserName) }; ClaimsIdentity userIdentity = new ClaimsIdentity(claims, "login"); ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity); await HttpContext.SignInAsync(principal); //寫入HttpContext return RedirectToAction("Index", "Test"); } }
在Startup中添加cookie認證服務並使用
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) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); //sqlserve services.AddDbContext<MyDbContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); //添加cookie認證服務 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Home/Index/"; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } //使用認證服務 app.UseAuthentication(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
修改Views/Home/Index.cshtml為下麵內容
@model CookieAuth.Models.User @{ ViewData["Title"] = "Home Page"; } <div class="row"> <div class="col-md-4"> <section> <form method="post" asp-action="Login"> <h4>Login</h4> <hr /> <div class="form-group"> <label asp-for="UserName"></label> <input asp-for="UserName" class="form-control" /> </div> <div class="form-group"> <label asp-for="UserPwd"></label> <input asp-for="UserPwd" type="password" class="form-control" /> </div> <div class="form-group"> <button type="submit" class="btn btn-default">登錄</button> </div> </form> </section> </div> </div>
在_Layout中添加一個導航欄
然後在Test控制器中添加認證特性
就可以啟動項目。
如果不沒輸入正確的地址是會被重定向到登錄頁面。
就這樣先,如果是已有項目 只需要在startup中添加cookie認證服務以及在login和logout方法中創建和銷毀聲明。
在controller或者action中添加啟動認證或者不啟用認證隨意配置