ASP.NET Identity的基本用法
早在2005年的時候,微軟隨著ASP.NET 推出了membership機制,十年磨一劍,如今的ASP.NET Identity是否足夠強大,一起來體會。
在VS2013下新建項目,選擇"ASP.NET Web應(yīng)用程序。",點擊"確定"。
選擇"MVC"模版。
創(chuàng)建的網(wǎng)站包括三個核心組件:
- 1、Microsoft.AspNet.Identity.EntityFramework
這是基于ASP.NET Identity的Entity Framework實現(xiàn),用來持久化ASP.NET Identity數(shù)據(jù)和架構(gòu),以及負責和SQL Server數(shù)據(jù)庫交互。
- 2、Microsoft.AspNet.Identity.Core
包含了ASP.NET Identity的核心接口,用來針對不同的持久層,比如Azure Table Storeage, NoSQL數(shù)據(jù)庫等做不同的實現(xiàn)。
- 3、Microsoft.AspNet.Identity.OWIN
OWIN是一個安全中間件,Microsoft在此基礎(chǔ)上作了再開發(fā),如記錄日志,產(chǎn)生cookie的時候用到。
各組件的依賴關(guān)系如圖:
F5運行項目。
點擊右上角的注冊按鈕,填寫注冊信息,點擊"注冊"按鈕,新用戶注冊成功并呈登錄狀態(tài)。
點擊VS2013的"停止調(diào)試"按鈕。
存儲的數(shù)據(jù)放在了哪呢?
右鍵App_Data,點擊"在文件資源管理器中打開文件",原來數(shù)據(jù)庫被存放在項目文件夾App_Data下了。
如何查看這些數(shù)據(jù)呢?
點擊VS2013的左上角"服務(wù)器資源管理器",右鍵"DefaultConnection",從中可以查看所有的數(shù)據(jù)。
比如用戶數(shù)據(jù)被存放在表"AspNetUsers"中。
點擊"注冊"按鈕,是把請求交給了AcccountController的Register這個Action。
[HttpPost][AllowAnonymous][ValidateAntiForgeryToken]public async Task<ActionResult> Register(RegisterViewModel model){ if (ModelState.IsValid) {var user = new ApplicationUser() { UserName = model.UserName };var result = await UserManager.CreateAsync(user, model.Password);if (result.Succeeded){ await SignInAsync(user, isPersistent: false); return RedirectToAction("Index", "Home");}else{ AddErrors(result);} } // 如果我們進行到這一步時某個地方出錯,則重新顯示表單 return View(model);}
以上,
- 通過ApplicationUser來實例化一個用戶
- 通過UserManager的靜態(tài)、異步方法CreateAsync創(chuàng)建用戶
- 通過異步方法SignInAsync來讓用戶登錄
private async Task SignInAsync(ApplicationUser user, bool isPersistent){ AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);}
以上
- 所有驗證的事交給了AuthenticationManager,負責登錄登出
- 把創(chuàng)建ClaimsIdentity交給了UserManager
至于登出,請求交給了AccountController的LogOff。
[HttpPost][ValidateAntiForgeryToken]public ActionResult LogOff(){ AuthenticationManager.SignOut(); return RedirectToAction("Index", "Home");}
還沒有看到ASP.NET Idenity有多少過人之處,讓時間來告訴我們。
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章:
1. ASP.NET MVC遍歷驗證ModelState的錯誤信息2. 使用EF Code First搭建簡易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移3. ASP.NET MVC使用Identity增刪改查用戶4. ASP.NET MVC使用Quartz.NET執(zhí)行定時任務(wù)5. ASP.NET MVC實現(xiàn)本地化和全球化6. asp.net core應(yīng)用docke部署到centos7的全過程7. ASP.Net Core(C#)創(chuàng)建Web站點的實現(xiàn)8. ASP.NET MVC限制同一個IP地址單位時間間隔內(nèi)的請求次數(shù)9. ASP.NET MVC解決上傳圖片臟數(shù)據(jù)的方法10. ASP.NET MVC獲取多級類別組合下的產(chǎn)品
