3分鐘快速學(xué)會(huì)在ASP.NET Core MVC中如何使用Cookie
一.Cookie是什么?
我的朋友問我cookie是什么,用來(lái)干什么的,可是我居然無(wú)法清楚明白簡(jiǎn)短地向其闡述cookie,這不禁讓我陷入了沉思:為什么我無(wú)法解釋清楚,我對(duì)學(xué)習(xí)的方法產(chǎn)生了懷疑!所以我們?cè)趯W(xué)習(xí)一個(gè)東西的時(shí)候,一定要做到知其然知其所以然。
HTTP協(xié)議本身是無(wú)狀態(tài)的。什么是無(wú)狀態(tài)呢,即服務(wù)器無(wú)法判斷用戶身份。Cookie實(shí)際上是一小段的文本信息)??蛻舳讼蚍?wù)器發(fā)起請(qǐng)求,如果服務(wù)器需要記錄該用戶狀態(tài),就使用response向客戶端瀏覽器頒發(fā)一個(gè)Cookie。客戶端瀏覽器會(huì)把Cookie保存起來(lái)。當(dāng)瀏覽器再請(qǐng)求該網(wǎng)站時(shí),瀏覽器把請(qǐng)求的網(wǎng)址連同該Cookie一同提交給服務(wù)器。服務(wù)器檢查該Cookie,以此來(lái)辨認(rèn)用戶狀態(tài)。
打個(gè)比方,這就猶如你辦理了銀行卡,下次你去銀行辦業(yè)務(wù),直接拿銀行卡就行,不需要身份證。
二.在.NET Core中嘗試
廢話不多說,干就完了,現(xiàn)在我們創(chuàng)建ASP.NET Core MVC項(xiàng)目,撰寫該文章時(shí)使用的.NET Core SDK 3.0 構(gòu)建的項(xiàng)目,創(chuàng)建完畢之后我們無(wú)需安裝任何包,
但是我們需要在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>(); }
在其中我們配置登錄頁(yè)面,其中 AddAuthentication 中是我們的方案名稱,這個(gè)是做什么的呢?很多小伙伴都懵懵懂懂表示很懵逼啊,我看很多人也是都寫得默認(rèn),那它到底有啥用,經(jīng)過我看AspNetCore源碼發(fā)現(xiàn)它這個(gè)是可以做一些配置的??聪旅娴拇a:
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 的變量就可以替換某些配置,在配置中一共有這幾項(xiàng),這無(wú)疑是幫助我們快速使用Cookie的好幫手~點(diǎn)個(gè)贊。
在源碼中可以看到Cookie默認(rèn)保存的時(shí)間是14天,這個(gè)時(shí)間我們可以去選擇,支持TimeSpan的那些類型。
public CookieAuthenticationOptions() { ExpireTimeSpan = TimeSpan.FromDays(14); ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter; SlidingExpiration = true; Events = new CookieAuthenticationEvents(); }
接下來(lái)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(); }
就拿出推出的源碼來(lái)看,其中獲取了Handler的某些信息,隨后將它轉(zhuǎn)換為 IAuthenticationSignOutHandler 接口類型,這個(gè)接口 as 接口,像是在地方實(shí)現(xiàn)了這個(gè)接口,然后將某些運(yùn)行時(shí)的值引用傳遞到該接口上。
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)建了某些實(shí)例,這里不再多說,因?yàn)樵创a深不見底,我也說不太清楚...只是想表達(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; }
最后我們?cè)陧?yè)面上想要獲取登錄的信息,可以通過 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é)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)我們的支持。
上一篇:沒有了
欄 目:ASP.NET
下一篇:沒有了
本文標(biāo)題:3分鐘快速學(xué)會(huì)在ASP.NET Core MVC中如何使用Cookie
本文地址:http://mengdiqiu.com.cn/a1/ASP_NET/10815.html
您可能感興趣的文章


閱讀排行
- 1C語(yǔ)言 while語(yǔ)句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹的示例代碼(圣誕
- 3利用C語(yǔ)言實(shí)現(xiàn)“百馬百擔(dān)”問題方法
- 4C語(yǔ)言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語(yǔ)言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語(yǔ)言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語(yǔ)言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-11vscode extension插件開發(fā)詳解
- 01-11VsCode插件開發(fā)之插件初步通信的方法
- 01-11如何給asp.net core寫個(gè)簡(jiǎn)單的健康檢查
- 01-11.net core高吞吐遠(yuǎn)程方法如何調(diào)用組件
- 01-11淺析.Net Core中Json配置的自動(dòng)更新
- 01-11.NET開發(fā)人員關(guān)于ML.NET的入門學(xué)習(xí)
- 01-11.NET Core 遷移躺坑記續(xù)集之Win下莫名其
- 01-11.net core webapi jwt 更為清爽的認(rèn)證詳解
- 01-11docker部署Asp.net core應(yīng)用的完整步驟
- 01-11ASP.NET Core靜態(tài)文件的使用方法
隨機(jī)閱讀
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-10C#中split用法實(shí)例總結(jié)
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 01-10delphi制作wav文件的方法
- 01-10使用C語(yǔ)言求解撲克牌的順子及n個(gè)骰子
- 04-02jquery與jsp,用jquery
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什
- 01-11ajax實(shí)現(xiàn)頁(yè)面的局部加載