3分钟快速学会在ASP.NET Core MVC中如何使用Cookie
 更新时间:2019年12月26日 08:38:48   作者:张子浩  

这篇文章主要给大家介绍了关于如何通过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相关的。

//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源码发现它这个是可以做一些配置的。看下面的代码:

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默认保存的时间是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 () =>
{
//注销登录的用户,相当于ASP.NET中的FormsAuthentication.SignOut
await HttpContext.SignOutAsync();
}).Wait();
return View();
}

就拿出推出的源码来看,其中获取了Handler的某些信息,随后将它转换为 IAuthenticationSignOutHandler 接口类型,这个接口 as 接口,像是在地方实现了这个接口,然后将某些运行时的值引用传递到该接口上。

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 中根据认证策略创建了某些实例,这里不再多说,因为源码深不见底,我也说不太清楚…只是想表达一下看源码的好处和坏处….

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地址:github.com/zaranetCore/aspNetCore_JsonwebToken/tree/master/src/Identity.Cookie/DotNetCore_Cookie_Sample
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对华域联盟的支持。

您可能感兴趣的文章:ASP.NET Core使用JWT认证授权的方法ASP.Net Core3.0中使用JWT认证的实现在 ASP.Net Core 中使用 MiniProfiler的方法

asp.net
mvc
cookie

相关文章
C#获取当前页面的URL示例代码获取当前页面的URL在某些情况下还是比较使用的,下面为大家介绍下如何通过C#以及Javascript获取当前页面的URL,感兴趣的朋友不要错过 2013-11-11
Image显示服务器上任意绝对路径下的图片(采用二进制流实现)有这样一个需求:数据库中存储的是照片所在的绝对路径(可以不在系统所在路径下),Image控件动态加载路径下的图片,另类实现方法,感兴趣的朋友可以参考下,或许本文对你学习二进制流有所帮助 2013-02-02
Asp.Net Mvc2 OA 工作流设计思路[图]回老家上班的新公司,第一个项目:OA。以前没有做过OA,因为设计到工作流这一块的东西,所以自己去进行了相关的了解,于是有了这篇博客(以下文字只是个人理解,高手漂过) 2012-10-10
asp.net微信开发(自定义会话管理)这篇文章主要介绍了asp.net微信开发中有关自定义会话管理的相关内容,需要的朋友可以参考下 2015-11-11
Asp.Net Oracle数据的通用操作类Asp.Net连接Oracle数据的通用操作类并且利用它对数据库查询、汇总、更新等操作演示 2009-12-12
asp.net SqlParameter关于Like的传参数无效问题用传参方式模糊查询searchName 2009-06-06
VisualStudio2019中为.NET Core WinForm App启用窗体设计器这篇文章主要介绍了VisualStudio2019中为.NET Core WinForm App启用窗体设计器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 2020-04-04
C# 添加文字水印类代码可以添加文字水印的c# 类函数。 2009-05-05
用WPF实现屏幕文字提示的实现方法本文介绍WPF应用程序实现在屏幕上显示一行或多行文字通知。它没有标题栏和最大化最小化等按钮,可以有半透明背景以使文字的显示更清晰,鼠标点击后提示消失。 2013-07-07
asp.net 点缩略图弹出随图片大小自动调整的页面程序用asp.net编写,功能主要是,点pic_small.Aspx页面的缩略图后弹出pic_all.aspx页面,pic_all.aspx页面的大小要根据图片大小自动调整 2009-06-06

最新评论

声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。