深入理解Aspnet Core之Identity(1)

来源:https://www.cnblogs.com/blue-tian/archive/2018/03/17/8589251.html
-Advertisement-
Play Games

最近學習asp.netcore 打算寫出來和大家分享,我計劃先寫Identity部分,會從開始asp.netocre identity的簡單實用開始,然後再去講解主要的類和自定義這些類。 主題:asp.netcore Identity 的簡單實用 創建項目: 使用asp.netcore 項目模版創建 ...


      最近學習asp.netcore 打算寫出來和大家分享,我計劃先寫Identity部分,會從開始asp.netocre identity的簡單實用開始,然後再去講解主要的類和自定義這些類。

主題:asp.netcore Identity 的簡單實用

創建項目:

使用asp.netcore 項目模版創建一個空(empty)項目,創建完成之後編輯.csproj文件,代碼如下

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /> <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
        Version="2.0.0" />
  </ItemGroup>
</Project>

 增加了

<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet"

        Version="2.0.0" />
 這個行代碼;
然後編輯 startup代碼文件,增加mvc,和認證部分
public void ConfigureServices(IServiceCollection services) 
{
            services.AddMvc();
}
        public void Configure(IApplicationBuilder app) 
{
            app.UseStatusCodePages();
            app.UseDeveloperExceptionPage();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
}

 配置Identity



現在我們配置identity的信息,包括配置的修改,添加user類

1創建user類

user類代表了用戶的賬號信息,比如登陸名,密碼,角色,email等信息,代碼如下:

using Microsoft.AspNetCore.Identity;
namespace DemoUser.Models
{
    public class AppUser:IdentityUser
    {
        
    }
}

 我們是繼承了 identityuser這個類,這個類已經包含了基本的用戶信息屬性,比如 登陸名,密碼 ,手機號等,該類的反編譯之後信息如下:

// Decompiled with JetBrains decompiler
// Type: Microsoft.AspNetCore.Identity.IdentityUser`1
// Assembly: Microsoft.Extensions.Identity.Stores, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// MVID: 7E04453E-9787-4C8F-ACD1-4ADA9BB7C88C
// Assembly location: /usr/local/share/dotnet/sdk/NuGetFallbackFolder/microsoft.extensions.identity.stores/2.0.1/lib/netstandard2.0/Microsoft.Extensions.Identity.Stores.dll

using System;

namespace Microsoft.AspNetCore.Identity
{
  /// <summary>Represents a user in the identity system</summary>
  /// <typeparam name="TKey">The type used for the primary key for the user.</typeparam>
  public class IdentityUser<TKey> where TKey : IEquatable<TKey>
  {
    /// <summary>
    /// Initializes a new instance of <see cref="T:Microsoft.AspNetCore.Identity.IdentityUser`1" />.
    /// </summary>
    public IdentityUser()
    {
    }

    /// <summary>
    /// Initializes a new instance of <see cref="T:Microsoft.AspNetCore.Identity.IdentityUser`1" />.
    /// </summary>
    /// <param name="userName">The user name.</param>
    public IdentityUser(string userName)
      : this()
    {
      this.UserName = userName;
    }

    /// <summary>Gets or sets the primary key for this user.</summary>
    public virtual TKey Id { get; set; }

    /// <summary>Gets or sets the user name for this user.</summary>
    public virtual string UserName { get; set; }

    /// <summary>Gets or sets the normalized user name for this user.</summary>
    public virtual string NormalizedUserName { get; set; }

    /// <summary>Gets or sets the email address for this user.</summary>
    public virtual string Email { get; set; }

    /// <summary>
    /// Gets or sets the normalized email address for this user.
    /// </summary>
    public virtual string NormalizedEmail { get; set; }

    /// <summary>
    /// Gets or sets a flag indicating if a user has confirmed their email address.
    /// </summary>
    /// <value>True if the email address has been confirmed, otherwise false.</value>
    public virtual bool EmailConfirmed { get; set; }

    /// <summary>
    /// Gets or sets a salted and hashed representation of the password for this user.
    /// </summary>
    public virtual string PasswordHash { get; set; }

    /// <summary>
    /// A random value that must change whenever a users credentials change (password changed, login removed)
    /// </summary>
    public virtual string SecurityStamp { get; set; }

    /// <summary>
    /// A random value that must change whenever a user is persisted to the store
    /// </summary>
    public virtual string ConcurrencyStamp { get; set; } = Guid.NewGuid().ToString();

    /// <summary>Gets or sets a telephone number for the user.</summary>
    public virtual string PhoneNumber { get; set; }

    /// <summary>
    /// Gets or sets a flag indicating if a user has confirmed their telephone address.
    /// </summary>
    /// <value>True if the telephone number has been confirmed, otherwise false.</value>
    public virtual bool PhoneNumberConfirmed { get; set; }

    /// <summary>
    /// Gets or sets a flag indicating if two factor authentication is enabled for this user.
    /// </summary>
    /// <value>True if 2fa is enabled, otherwise false.</value>
    public virtual bool TwoFactorEnabled { get; set; }

    /// <summary>
    /// Gets or sets the date and time, in UTC, when any user lockout ends.
    /// </summary>
    /// <remarks>A value in the past means the user is not locked out.</remarks>
    public virtual DateTimeOffset? LockoutEnd { get; set; }

    /// <summary>
    /// Gets or sets a flag indicating if the user could be locked out.
    /// </summary>
    /// <value>True if the user could be locked out, otherwise false.</value>
    public virtual bool LockoutEnabled { get; set; }

    /// <summary>
    /// Gets or sets the number of failed login attempts for the current user.
    /// </summary>
    public virtual int AccessFailedCount { get; set; }

    /// <summary>Returns the username for this user.</summary>
    public override string ToString()
    {
      return this.UserName;
    }
  }
}

 這個類已經定義好了一些關於賬戶的屬性,,假如我們覺得還需要添加自定義的屬性比如 用戶的地址,我們只需要在我們繼承的類添加自定義的屬性即可;

創建資料庫上下文:

下麵我們要創建一個數據上下文用於連接資料庫,代碼如下:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace DemoUser.Models
{
    public class AppIdentityDbContext :IdentityDbContext<AppUser>
    {
        public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options)
            : base(options) { }
    }
}

 配置資料庫連接字元串:

為了連接資料庫我們要配置一個連接字元串,修改appsettings.json文件如下:

 

{
  "Data": {
    "AppStoreIdentity": {
      "ConnectionString": "Server=192.168.0.4;Database=IdentityUsers;User ID =SA; Password=!@#"
    } 
  }
}

 

 下麵我們需要在startup類配置連接字元串到資料庫上下文;

public void ConfigureServices(IServiceCollection services) 
{
            services.AddDbContext<AppIdentityDbContext>(options =>
                options.UseSqlServer(
                    Configuration["Data:AppStoreIdentity:ConnectionString"]));
            services.AddIdentity<AppUser, IdentityRole>()
                .AddEntityFrameworkStores<AppIdentityDbContext>()
                .AddDefaultTokenProviders();
            services.AddMvc();
        }

 創建資料庫:

下麵我們需要用EFCore去生成一個資料庫:

打開控制台,定位到當前的項目,輸入:

dotnet ef migrations add Initial

然後就會產生一個migrations文件夾,裡面是我們要生成資料庫的代碼;
然後 在控制台輸入:
dotnet ef database update

這樣我們的資料庫就生成了







這裡是我上傳的github倉庫地址:https://github.com/bluetianx/AspnetCoreExample

後續:

我會創建一個具有增刪改查的賬戶管理界面

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 說在前面:1.學習緣由及學習途徑: 在學了Python,c#(自認為未精通)之後,我決定學一下C++。 於是去網上找視頻教程,發現都不適合我這種有一定基礎的自學者,要麼是不完整的高級教程,要麼是零基礎的浪費時間。 於是向摯友購入一本二手《C++ primer plus》,在空餘時間翻一翻,自學。 2 ...
  • 前言 本博文主要講解的知識點如下: 校驗器 統一處理異常 RESTful 攔截器 Validation 在我們的Struts2中,我們是繼承ActionSupport來實現校驗的...它有兩種方式來實現校驗的功能 手寫代碼 XML配置 這兩種方式也是可以特定處理方法或者整個Action的 而Spri ...
  • //凱魯嘎吉 - 博客園 http://www.cnblogs.com/kailugaji/ 漢諾塔是由三根桿子A,B,C組成的。A桿上有n個(n>1)穿孔圓盤,盤的尺寸由下到上依次變小。要求按下列規則將所有圓盤移至C桿:每次只能移動一個圓盤;大盤不能疊在小盤上面。提示:可將圓盤臨時置於B桿,也可將 ...
  • 今天我們一起來看一下WPF窗體之間的交互-窗體之間的傳值。有兩個窗體,一個是父窗體,一個是子窗體。要將父窗體的文本框中的值傳遞給子窗體中的控制項。我們該怎麼實現? 接下來我們一起來實現窗體之間的傳值,在父窗體上我們放兩個控制項,一個文本框TxtMessage,另一個是按鈕BtnSend.子窗體上放一個文 ...
  • 軟體功能: 使用C#實現PC串口通訊 支持定時發送 支持16進位(hex) ASCII UTF-8 Unicode 四種編碼格式 支持配置文件的保存和讀取 可以可以顯示發送歷史 可以統計總的發送位元組數和接受位元組數 軟體界面: C#源碼: using System; using System.Coll ...
  • 自己在空閑時分整合、編寫了一款小軟體程式,命名為魔法兔子,希望大家可以提出意見和指導,此篇文章主要為軟體的部分截圖和介紹。 軟體詳情: 1.首先是登錄,註冊界面。 可以註冊自己的賬號,後臺是騰訊雲伺服器,資料庫採用了SQL Server,運用了Winform編寫。 1)在註冊界面填入正確的賬號,密碼 ...
  • 在Angularjs顯示html文本,如果按照一般處理它。它只能頁中顯示沒經解釋文本。在ASP.NET MVC添加一個控制器: 創建angularjs控制器: pilotApp.controller('ShowHtmlCtrl', ['$scope','$sce', function ($scope ...
  • 對於一個應用來說界面的重要性無言而喻,而Web應用的界面是使用Html+Css以及Javascript實現的,ASP.NET MVC是一個用來構建Web應用的框架,它的界面也是Html實現的,對於一些開發團隊來說,一般Web項目會存在專業的UI前端工程師和後端工程師,前端工程師可能只懂設計和Html ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...