一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - ASP.NET教程 - 3分鐘快速學會在ASP.NET Core MVC中如何使用Cookie

3分鐘快速學會在ASP.NET Core MVC中如何使用Cookie

2020-06-24 15:25張子浩 ASP.NET教程

這篇文章主要給大家介紹了關于如何通過3分鐘快速學會在ASP.NET Core MVC中使用Cookie的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用ASP.NET具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧

一.Cookie是什么?

我的朋友問我cookie是什么,用來干什么的,可是我居然無法清楚明白簡短地向其闡述cookie,這不禁讓我陷入了沉思:為什么我無法解釋清楚,我對學習的方法產生了懷疑!所以我們在學習一個東西的時候,一定要做到知其然知其所以然。

HTTP協議本身是無狀態的。什么是無狀態呢,即服務器無法判斷用戶身份。Cookie實際上是一小段的文本信息)。客戶端向服務器發起請求,如果服務器需要記錄該用戶狀態,就使用response向客戶端瀏覽器頒發一個Cookie。客戶端瀏覽器會把Cookie保存起來。當瀏覽器再請求該網站時,瀏覽器把請求的網址連同該Cookie一同提交給服務器。服務器檢查該Cookie,以此來辨認用戶狀態。

打個比方,這就猶如你辦理了銀行卡,下次你去銀行辦業務,直接拿銀行卡就行,不需要身份證。

二.在.NET Core中嘗試

廢話不多說,干就完了,現在我們創建ASP.NET Core MVC項目,撰寫該文章時使用的.NET Core SDK 3.0 構建的項目,創建完畢之后我們無需安裝任何包,

但是我們需要在Startup中添加一些配置,用于Cookie相關的。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//public const string CookieScheme = "YourSchemeName";
  public Startup(IConfiguration configuration)
  {
   Configuration = configuration;
  }
  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)
  {
   //CookieAuthenticationDefaults.AuthenticationScheme Cookies Default Value
   //you can change scheme
   services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => {
     options.LoginPath = "/LoginOrSignOut/Index/";
    });
   services.AddControllersWithViews();
   // is able to also use other services.
   //services.AddSingleton<IConfigureOptions<CookieAuthenticationOptions>, ConfigureMyCookie>();
  }

在其中我們配置登錄頁面,其中 AddAuthentication 中是我們的方案名稱,這個是做什么的呢?很多小伙伴都懵懵懂懂表示很懵逼啊,我看很多人也是都寫得默認,那它到底有啥用,經過我看AspNetCore源碼發現它這個是可以做一些配置的。看下面的代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
internal class ConfigureMyCookie : IConfigureNamedOptions<CookieAuthenticationOptions>
 {
  // You can inject services here
  public ConfigureMyCookie()
  {}
  public void Configure(string name, CookieAuthenticationOptions options)
  {
   // Only configure the schemes you want
   //if (name == Startup.CookieScheme)
   //{
    // options.LoginPath = "/someotherpath";
   //}
  }
  public void Configure(CookieAuthenticationOptions options)
   => Configure(Options.DefaultName, options);
 }

在其中你可以定義某些策略,隨后你直接改變 CookieScheme 的變量就可以替換某些配置,在配置中一共有這幾項,這無疑是幫助我們快速使用Cookie的好幫手~點個贊。

3分鐘快速學會在ASP.NET Core MVC中如何使用Cookie

在源碼中可以看到Cookie默認保存的時間是14天,這個時間我們可以去選擇,支持TimeSpan的那些類型。

?
1
2
3
4
5
6
7
public CookieAuthenticationOptions()
  {
   ExpireTimeSpan = TimeSpan.FromDays(14);
   ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
   SlidingExpiration = true;
   Events = new CookieAuthenticationEvents();
  }

接下來LoginOrOut Controller,我們模擬了登錄和退出,通過 SignInAsync 和 SignOutAsync 方法。

?
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
29
30
[HttpPost]
  public async Task<IActionResult> Login(LoginModel loginModel)
  {
   if (loginModel.Username == "haozi zhang" &&
    loginModel.Password == "123456")
   {
    var claims = new List<Claim>
     {
     new Claim(ClaimTypes.Name, loginModel.Username)
     };
    ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "login"));
    await HttpContext.SignInAsync(principal);
    //Just redirect to our index after logging in.
    return Redirect("/Home/Index");
   }
   return View("Index");
  }
  /// <summary>
  /// this action for web lagout
  /// </summary>
  [HttpGet]
  public IActionResult Logout()
  {
   Task.Run(async () =>
   {
    //注銷登錄的用戶,相當于ASP.NET中的FormsAuthentication.SignOut
    await HttpContext.SignOutAsync();
   }).Wait();
   return View();
  }

就拿出推出的源碼來看,其中獲取了Handler的某些信息,隨后將它轉換為 IAuthenticationSignOutHandler 接口類型,這個接口 as 接口,像是在地方實現了這個接口,然后將某些運行時的值引用傳遞到該接口上。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public virtual async Task SignOutAsync(HttpContext context, string scheme, AuthenticationProperties properties)
  {
   if (scheme == null)
   {
    var defaultScheme = await Schemes.GetDefaultSignOutSchemeAsync();
    scheme = defaultScheme?.Name;
    if (scheme == null)
    {
     throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultSignOutScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).");
    }
   }
   var handler = await Handlers.GetHandlerAsync(context, scheme);
   if (handler == null)
   {
    throw await CreateMissingSignOutHandlerException(scheme);
   }
   var signOutHandler = handler as IAuthenticationSignOutHandler;
   if (signOutHandler == null)
   {
    throw await CreateMismatchedSignOutHandlerException(scheme, handler);
   }
   await signOutHandler.SignOutAsync(properties);
  }

其中 GetHandlerAsync 中根據認證策略創建了某些實例,這里不再多說,因為源碼深不見底,我也說不太清楚...只是想表達一下看源碼的好處和壞處....

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public async Task<IAuthenticationHandler> GetHandlerAsync(HttpContext context, string authenticationScheme)
  {
   if (_handlerMap.ContainsKey(authenticationScheme))
   {
    return _handlerMap[authenticationScheme];
   }
 
   var scheme = await Schemes.GetSchemeAsync(authenticationScheme);
   if (scheme == null)
   {
    return null;
   }
   var handler = (context.RequestServices.GetService(scheme.HandlerType) ??
    ActivatorUtilities.CreateInstance(context.RequestServices, scheme.HandlerType))
    as IAuthenticationHandler;
   if (handler != null)
   {
    await handler.InitializeAsync(scheme, context);
    _handlerMap[authenticationScheme] = handler;
   }
   return handler;
  }

最后我們在頁面上想要獲取登錄的信息,可以通過 HttpContext.User.Claims 中的簽名信息獲取。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@using Microsoft.AspNetCore.Authentication
<h2>HttpContext.User.Claims</h2>
<dl>
 @foreach (var claim in User.Claims)
 {
  <dt>@claim.Type</dt>
  <dd>@claim.Value</dd>
 }
</dl>
<h2>AuthenticationProperties</h2>
<dl>
 @foreach (var prop in (await Context.AuthenticateAsync()).Properties.Items)
 {
  <dt>@prop.Key</dt>
  <dd>@prop.Value</dd>
 }
</dl>

三.最后效果以及源碼地址#

3分鐘快速學會在ASP.NET Core MVC中如何使用Cookie

GitHub地址:https://github.com/zaranetCore/aspNetCore_JsonwebToken/tree/master/src/Identity.Cookie/DotNetCore_Cookie_Sample

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。

原文鏈接:https://www.cnblogs.com/ZaraNet/p/12099286.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 99久久综合 | 99九九国产精品免费视频 | 亚洲人成高清毛片 | 亚洲国产天堂久久精品网 | 久久中文字幕无线观看 | 国产伦精品一区二区三区免费迷 | 女人爽到喷水的视频免费看 | 国产成人精品免费视频大全五级 | 亚洲日日做天天做日日谢 | 好爽好粗 | 午夜办公室在线观看高清电影 | 午夜福利电影网站鲁片大全 | 欧美在线一 | 国产剧情麻豆刘玥视频 | 男女视频在线观看网站 | 91混血大战上海双胞胎 | 高h短篇辣肉各种姿势bl | 91sao国产在线观看 | 亚洲国产精品网站久久 | 婷婷丁香视频 | 欧美人与日本人xx在线视频 | 成人啪啪漫画全文阅读 | 成年美女黄网站色视频大全免费 | 日韩欧美推理片免费在线播放 | 成人网中文字幕色 | 污翼鸟 | 紧身短裙女教师波多野 | 精品国产自在现线久久 | 高h辣h双处全是肉军婚 | 99成人国产精品视频 | 青青草在视线频久久 | 无码乱人伦一区二区亚洲 | 日本 在线播放 | 肉搏潘金莲三级18春 | 久久精品视在线观看85 | 精品国产影院 | 亚州男人的天堂 | 关晓彤一级做a爰片性色毛片 | 好涨好大我快受不了了视频网 | 欧美一区二区三区四区视频 | 手机国产乱子伦精品视频 |