ASP.NET Core MVC 網站學習筆記


ASP.NET Core MVC 網站學習筆記

魏劉宏 2020 年 2 月 17 日

最近因為” 新冠” 疫情在家辦公,學習了 ASP.NET Core MVC 網站的一些知識,記錄如下。

 

一、新建項目及基本結構

 

我們要新建的是 “ASP.NET Core Web 應用程序” 類型的項目:

 

起名之后選擇 .NET Core 分類下的 “Web 應用程序 (模型視圖控制器)” 模板,也就是 MVC 類型的模板,然后創建即可:

 

創建后結構如下圖:

 

wwwroot 存放網站的 js、css 等前端文件,Models 存放模型類,Views 存放視圖文件,Controllers 存放控制器;

appsettings.json 用於配置,比如可以在其中加入數據庫連接字符串:

 

Programs 是程序入口,實際的啟動工作通過 Startup 來進行。

 

二、實體模型和 EF 框架

 

我們可以在 Models 文件夾下添加實體類,並給字段添加一些特性:

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

// 存放實體類 Entity
namespace EasyBlog.Models
{
    /// <summary>
    /// 用戶表
    /// </summary>
    public class InfoUser
    {
        [Key] //非ID的主鍵需要
        [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; }
    }
}

 

再添加一個 數據庫上下文類,繼承 DbContext :

using Microsoft.EntityFrameworkCore;

namespace EasyBlog.Models
{
    /// <summary>
    /// EntityFrameworkCore(實體框架) <span class='wp_keywordlink_affiliate'><a href="http://dlgcy.com/tag/ef/" title="View all posts in EF" target="_blank">EF</a></span>(Code First)
    /// </summary>
    public class DbWlh : DbContext
    {
        public DbWlh(DbContextOptions<DbWlh> options) : base(options)
        {
        }

        public DbSet<InfoUser> InfoUsers { get; set; }
        public DbSet<InfoBlog> InfoBlogs { get; set; }
        public DbSet<InfoReply> InfoReplies { get; set; }
        public DbSet<InfoLog> InfoLogs { get; set; }
    }
}

 

在 Startup 中的 ConfigureServices 方法中注冊數據庫上下文,用到了數據庫上下文類和數據庫連接字符串名稱:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    // 注冊數據庫上下文
    // 需要包:Microsoft.EntityFrameworkCore.sqlserver 和 Microsoft.EntityFrameworkCore.Tools
    services.AddDbContext<DbWlh>(options => 
                options.UseSqlServer(Configuration.GetConnectionString("DbWlh"))); 
}

 

現在我們可以打開” 程序包管理器控制台”(在” 工具”—”NuGet 包管理器” 中)了,敲入命令 “add-migration init” 來添加新的數據庫” 遷移”,其中”init” 是遷移的名稱。

 

添加的” 遷移” 都保存在 Migrations 目錄下:

 

添加完” 遷移” 之后,就可以使用命令”update-database” 將改動更新到數據庫中了。

 

三、MVC

 

進行到這一步后,最簡單的添加一套 MVC 增刪改查功能(准確地說只添加了 VC)的方法就是,在 Controllers 文件夾上右鍵 —” 添加”—” 控制器”,然后選擇 “視圖使用 Entity Framework 的 MVC 控制器”:

 

接下來選擇好模型類、數據上下文類,勾上” 生成視圖”,點擊” 添加” 即可:

 

這樣就不光生成了控制器,還在 Views 文件夾生成了相應的增刪改查頁面:

 

當然,你也可以自己在控制器里寫方法,然后在”return View ()” 的地方右鍵 —” 添加視圖”,這樣來添加視圖:

 

四、身份驗證

 

我們首先還是在 Startup 中的 ConfigureServices 方法中配置使用 Cookie 方式來做身份驗證:

代碼:

public const string CookieScheme = "Cookies";

    // 配置驗證;
    services.AddAuthentication(CookieScheme)
        .AddCookie(CookieScheme, option =>
        {
            option.LoginPath = new PathString("/account/login");  //登陸的路徑
            option.AccessDeniedPath = new PathString("/account/denied");
        });

 

在 Configure 方法中啟用驗證:

代碼: app.UseAuthentication(); // 啟用驗證; 

 

然后在需要驗證(登陸)才能用的控制器上標上”[Authorize]” 特性:

 

這樣如果未通過驗證就訪問,就會跳轉到驗證頁面(在 Startup 中配置過的)。

 

至於登陸成功的驗證信息的保存則使用以下代碼:

// 保存驗證結果;
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, userName));
var claimsIdentity = new ClaimsIdentity(claims, "Cookies");
await HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity));

 

這樣再訪問需要驗證的頁面,就能順利通過了,而且可以使用”User.Identity.Name” 的形式獲取到需要的數據。

 

好了,暫時就說這么多吧,再見。

 

首發:http://dlgcy.com/asp-net-core-mvc-learning/

 


免責聲明!

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



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