ASP.NET Core MVC創建與登入驗證


一,構建web應用

1.選擇c#-所有平台-web  找到ASP.NET Core web應用程序

 

 2.項目命名之后轉至如下界面:選擇Web應用程序(模型視圖控制器)。

 

Ok點擊創建,這個項目的基本框架就生成了。

 

二,EF-Code First 數據遷移

1,在Models里面新建實體類和數據庫上下文類,並添加相對應的引用和框架

 

具體代碼如下:

 實體類:

復制代碼
復制代碼
    public class InfoUser
    {
        [Key]
        [StringLength(10)]
        [DisplayName("用戶名")]
        [Required(ErrorMessage = "用戶名不能為空")]
        public string UserName { get; set; }
        [StringLength(16)]
        [DisplayName("密碼")]
        [Required(ErrorMessage = "密碼不能為空")]
        public string Password { get; set; }
        [DisplayName("創建日期")]
        public DateTime DTCreate { get; set; }
        [DisplayName("登陸日期")]
        public DateTime DTLogin { get; set; }

        public byte[] HeaderImg { get; set; }
    }
    /// <summary>
    /// 博客表
    /// </summary>
    public class InfoBlog
    {
        public int ID { get; set; }
        [StringLength(10)]
        public string UserName { get; set; }
        [StringLength(64)]
        public string Title { get; set; }

        public string Content { get; set; }
        public int VisitCount { get; set; }
        public DateTime DTCreate { get; set; }
    }
    /// <summary>
    /// 回復表
    /// </summary>
    public class InfoReply
    {
        public int ID { get; set; }
        public int BlogID { get; set; }
        [StringLength(10)]
        public string UserName { get; set; }
        public string Content { get; set; }
        public DateTime DTCreate { get; set; }
    }
    /// <summary>
    /// 日志表
    /// </summary>
    public class InfoLog
    {
        public int ID { get; set; }
        [StringLength(64)]
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTime DTCerate { get; set; }

    }
復制代碼
復制代碼

上下文類(需要繼承DbContext):

復制代碼
復制代碼
 public class DBXlp : DbContext
    {
        public DBXlp(DbContextOptions<DBXlp> options)
         : base(options)
        {

        }
        //add-migration init update-database 
        public DbSet<InfoUser> InfoUsers { get; set; }
        public DbSet<InfoBlog> InfoBlogs { get; set; }
        public DbSet<InfoReply> InfoReplies { get; set; }
        public DbSet<InfoLog> InfoLogs { get; set; }

    }
復制代碼
復制代碼

 

2,通過NuGet添加下面的兩個包

 

 

3,在appsettings.json里面添加連接數據庫的字符串

 

1
2
3
4
5
6
7
8
9
10
11
12
13
{
     "ConnectionStrings": {
       "DbXlp": "Server=.;Database=dbXlp;User id=sa;Password=123456"
     },
     "Logging": {
       "LogLevel": {
         "Default": "Information",
         "Microsoft": "Warning",
         "Microsoft.Hosting.Lifetime": "Information"
       }
     },
     "AllowedHosts": "*"
   }

  

4,然后在 Startup.cs 的 ConfigureServices(IServiceCollection services) 中,我們作為一個服務注冊了上下文對象。

services.AddDbContext<DBXlp>(options=>options.UseSqlServer(Configuration.GetConnectionString("DbXlp")));

5,打開 工具->NuGet包管理器->程序包管理器控制台

  1. 輸入命令:add-migration init(可隨意)(為掛起的Model變化添加遷移腳本 )
  2. 輸入命令:update-database( 將掛起的遷移更新到數據庫 )

 

 Ok 可以看到下面數據庫里已經有了對應表信息!

三,使用Identity進行登錄驗證

在Startup中:

 1.定義一個string類型的CookieScheme作為認證方案

1
public  const  string  CookieScheme =  "Cookies" ;

2.ConfigureServices中使用AddCookie設置選項

 

1
2
3
4
5
6
7
8
services.AddAuthentication(CookieScheme)
         .AddCookie(CookieScheme, option =>
         {
             // 登錄路徑:這是當用戶試圖訪問資源但未經過身份驗證時,程序將會將請求重定向到這個相對路徑。
             option.LoginPath =  new  PathString( "/account/login" );
             // 禁止訪問路徑:當用戶試圖訪問資源時,但未通過該資源的任何授權策略,請求將被重定向到這個相對路徑
             option.AccessDeniedPath =  new  PathString( "/account/denied" );
         });

  

3.在Configure方法中使用 UseAuthentication來調用認證中間件(如下圖所示位置)

 

控制器里面:

創建一個包含用戶信息的 cookie可以構造一個ClaimsPrincipal。用戶信息會被序列化然后保存在cookie 里面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public  async Task<ActionResult> Logining()
   {
       var  userName = Request.Form[ "UserName" ];
       var  password = Request.Form[ "Password" ];
       var  item = db.InfoUsers.Find(userName);
       if  (item !=  null  && password == item.Password)
       {
           item.DTLogin = DateTime.Now;
           db.SaveChanges();
           //用Claim來構造一個ClaimsIdentity,然后調用 SignInAsync 方法。
           var  claims =  new  List<Claim>();
           claims.Add( new  Claim(ClaimTypes.Name, userName));
           var  claimsIdentity =  new  ClaimsIdentity(claims,  "Cookies" );
           //登錄
           await HttpContext.SignInAsync( "Cookies" new  ClaimsPrincipal(claimsIdentity));
           return  RedirectToAction( "Index" "Blog" );
       }
       else
           ViewBag.Msg =  "登陸失敗" ;
       return  View();
   }<br>
   public  async Task<IActionResult> Logout()
   {
       //退出
       await HttpContext.SignOutAsync( "Cookies" );
       return  RedirectToAction( "Index" "Home" );
 
   }

然后我們只需要對那些需要授權登陸才能執行的界面或者操作標記[Authorize]即可:

最后我們也可以在Razor中判斷是否授權成功:

1
2
3
4
5
6
7
8
9
@if (User.Identity.IsAuthenticated)
{
<textarea id= "TextArea1"  rows= "10"  class= "form-control" ></textarea>
     <button onclick= "Reply()"  class= "btn btn-primary" >回復</button>
}
else
{
     <a asp-action= "Login"  asp-controller= "Account" >登錄</a>
}

  https://www.cnblogs.com/jiangyunfeng/p/12360520.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM