3分鐘快速學(xué)會在ASP.NET Core MVC中如何使用Cookie
一.Cookie是什么?
我的朋友問我cookie是什么,用來干什么的,可是我居然無法清楚明白簡短地向其闡述cookie,這不禁讓我陷入了沉思:為什么我無法解釋清楚,我對學(xué)習(xí)的方法產(chǎn)生了懷疑!所以我們在學(xué)習(xí)一個東西的時候,一定要做到知其然知其所以然。
HTTP協(xié)議本身是無狀態(tài)的。什么是無狀態(tài)呢,即服務(wù)器無法判斷用戶身份。Cookie實際上是一小段的文本信息)。客戶端向服務(wù)器發(fā)起請求,如果服務(wù)器需要記錄該用戶狀態(tài),就使用response向客戶端瀏覽器頒發(fā)一個Cookie??蛻舳藶g覽器會把Cookie保存起來。當(dāng)瀏覽器再請求該網(wǎng)站時,瀏覽器把請求的網(wǎng)址連同該Cookie一同提交給服務(wù)器。服務(wù)器檢查該Cookie,以此來辨認(rèn)用戶狀態(tài)。
打個比方,這就猶如你辦理了銀行卡,下次你去銀行辦業(yè)務(wù),直接拿銀行卡就行,不需要身份證。
二.在.NET Core中嘗試
廢話不多說,干就完了,現(xiàn)在我們創(chuàng)建ASP.NET Core MVC項目,撰寫該文章時使用的.NET Core SDK 3.0 構(gòu)建的項目,創(chuàng)建完畢之后我們無需安裝任何包,
但是我們需要在Startup中添加一些配置,用于Cookie相關(guān)的。
//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 中是我們的方案名稱,這個是做什么的呢?很多小伙伴都懵懵懂懂表示很懵逼啊,我看很多人也是都寫得默認(rèn),那它到底有啥用,經(jīng)過我看AspNetCore源碼發(fā)現(xiàn)它這個是可以做一些配置的。看下面的代碼:
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的好幫手~點個贊。

在源碼中可以看到Cookie默認(rèn)保存的時間是14天,這個時間我們可以去選擇,支持TimeSpan的那些類型。
public CookieAuthenticationOptions()
{
ExpireTimeSpan = TimeSpan.FromDays(14);
ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
SlidingExpiration = true;
Events = new CookieAuthenticationEvents();
}
接下來LoginOrOut Controller,我們模擬了登錄和退出,通過 SignInAsync 和 SignOutAsync 方法。
[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 () =>
{
//注銷登錄的用戶,相當(dāng)于ASP.NET中的FormsAuthentication.SignOut
await HttpContext.SignOutAsync();
}).Wait();
return View();
}
就拿出推出的源碼來看,其中獲取了Handler的某些信息,隨后將它轉(zhuǎn)換為 IAuthenticationSignOutHandler 接口類型,這個接口 as 接口,像是在地方實現(xiàn)了這個接口,然后將某些運(yùn)行時的值引用傳遞到該接口上。
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 中根據(jù)認(rèn)證策略創(chuàng)建了某些實例,這里不再多說,因為源碼深不見底,我也說不太清楚...只是想表達(dá)一下看源碼的好處和壞處....
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 中的簽名信息獲取。
@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>
三.最后效果以及源碼地址#

GitHub地址:https://github.com/zaranetCore/aspNetCore_JsonwebToken/tree/master/src/Identity.Cookie/DotNetCore_Cookie_Sample
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。
- ASP.NET?Core中Cookie驗證身份用法詳解
- asp.core?同時兼容JWT身份驗證和Cookies?身份驗證兩種模式(示例詳解)
- .NET?Core支持Cookie和JWT混合認(rèn)證、授權(quán)的方法
- asp.net core3.1cookie和jwt混合認(rèn)證授權(quán)實現(xiàn)多種身份驗證方案
- ASP.NET Core 使用Cookie驗證身份的示例代碼
- asp.net core中如何使用cookie身份驗證
- ASP.NET學(xué)習(xí)CORE中使用Cookie身份認(rèn)證方法
- 詳解在ASP.NET Core 中使用Cookie中間件
- 詳解ASP.NET與ASP.NET Core用戶驗證Cookie并存解決方案
- ASP.NET?Core在WebApi項目中使用Cookie
相關(guān)文章
Asp.Net套用母版頁后元素ID不一致(個人總結(jié))
這篇文章主要介紹了Asp.Net套用母版頁后元素ID不一致(個人總結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
ASP.NET仿新浪微博下拉加載更多數(shù)據(jù)瀑布流效果
本篇文章介紹了如何實現(xiàn)下拉加載更多數(shù)據(jù)瀑布流的效果,這種效果最近很流行,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2015-07-07
Asp.net實時顯示文本框字?jǐn)?shù)實現(xiàn)代碼
實時顯示文本框字?jǐn)?shù)在日常開發(fā)中很常見,也很實用,接下來為大家介紹下如何實現(xiàn)實時顯示,感興趣的朋友可以參考下哈,希望可以幫助到你2013-04-04
httpHandler實現(xiàn).Net無后綴名Web訪問的實現(xiàn)解析
有時候我們看到很多網(wǎng)站是網(wǎng)址是沒有后綴名的,其實.net中可以通過httpHandler來實現(xiàn)。2011-10-10
.NET6使用微信小程序授權(quán)登錄獲取手機(jī)號
小程序手機(jī)號授權(quán)是在里打開小程序時彈窗請求允許使用某些功能,比如授權(quán)獲取用戶信息、授權(quán)獲取手機(jī)號等,本文主要介紹了.NET6使用微信小程序授權(quán)登錄獲取手機(jī)號,感興趣的可以了解一下2023-08-08
xpath的數(shù)據(jù)和節(jié)點類型以及XPath中節(jié)點匹配的基本方法
xpath的數(shù)據(jù)和節(jié)點類型以及XPath中節(jié)點匹配的基本方法,學(xué)習(xí)xpath的朋友可以參考下。2010-09-09

