一.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();
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 == "")
{
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地址:https://github.com/zaranetCore/aspNetCore_JsonwebToken/tree/master/src/Identity.Cookie/DotNetCore_Cookie_Sample

三分钟学会在ASP.NET Core MVC 中使用Cookie的更多相关文章

  1. 数据呈现到 ASP.NET Core MVC 中展示

    终于要将数据呈现到 ASP.NET Core MVC 中的 视图 上了 将数据从控制器传递到视图的三种方法 在 ASP.NET Core MVC 中,有 3 种方法可以将数据从控制器传递到视图: 使用 ...

  2. 006.Adding a controller to a ASP.NET Core MVC app with Visual Studio -- 【在asp.net core mvc 中添加一个控制器】

    Adding a controller to a ASP.NET Core MVC app with Visual Studio 在asp.net core mvc 中添加一个控制器 2017-2-2 ...

  3. 007.Adding a view to an ASP.NET Core MVC app -- 【在asp.net core mvc中添加视图】

    Adding a view to an ASP.NET Core MVC app 在asp.net core mvc中添加视图 2017-3-4 7 分钟阅读时长 本文内容 1.Changing vi ...

  4. 008.Adding a model to an ASP.NET Core MVC app --【在 asp.net core mvc 中添加一个model (模型)】

    Adding a model to an ASP.NET Core MVC app在 asp.net core mvc 中添加一个model (模型)2017-3-30 8 分钟阅读时长 本文内容1. ...

  5. ASP.NET Core MVC中的 [Required]与[BindRequired]

    在开发ASP.NET Core MVC应用程序时,需要对控制器中的模型校验数据有效性,元数据注释(Data Annotations)是一个完美的解决方案. 元数据注释最典型例子是确保API的调用者提供 ...

  6. ASP.NET Core MVC中URL和数据模型的匹配

    Http GET方法 首先我们来看看GET方法的Http请求,URL参数和ASP.NET Core MVC中Controller的Action方法参数匹配情况. 我定义一个UserController ...

  7. ASP.NET Core MVC 中的 [Controller] 和 [NonController]

    前言 我们知道,在 MVC 应用程序中,有一部分约定的内容.其中关于 Controller 的约定是这样的. 每个 Controller 类的名字以 Controller 结尾,并且放置在 Contr ...

  8. ASP.NET Core MVC 中设置全局异常处理方式

    在asp.net core mvc中,如果有未处理的异常发生后,会返回http500错误,对于最终用户来说,显然不是特别友好.那如何对于这些未处理的异常显示统一的错误提示页面呢? 在asp.net c ...

  9. ASP.NET Core MVC中构建Web API

    在ASP.NET CORE MVC中,Web API是其中一个功能子集,可以直接使用MVC的特性及路由等功能. 在成功构建 ASP.NET CORE MVC项目之后,选中解决方案,先填加一个API的文 ...

随机推荐

  1. 《DSP using MATLAB》Problem 8.1

    代码: %% ------------------------------------------------------------------------ %% Output Info about ...

  2. SprigBoot中的 WebMvcConfigurer与 WebMvcConfigurerAdapter和 WebMvcConfigurationSupport

    WebMvcConfigurationAdapter 过时? 在SpringBoot2.0之后的版本中WebMvcConfigurerAdapter过时了,所以我们一般采用的是如下的两种的解决的方法. ...

  3. mv- Linux必学的60个命令

    1.作用 mv命令用来为文件或目录改名,或者将文件由一个目录移入另一个目录中,它的使用权限是所有用户.该命令如同DOS命令中的ren和move的组合. 2.格式 mv[options] 源文件或目录 ...

  4. Leetcode152. Maximum Product Subarray乘积的最大子序列

    给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数). 示例 1: 输入: [2,3,-2,4] 输出: 6 解释: 子数组 [2,3] 有最大乘积 6. 示例 2 ...

  5. 60行JavaScript代码俄罗斯方块

    教你看懂网上流传的60行JavaScript代码俄罗斯方块游戏   早就听说网上有人仅仅用60行JavaScript代码写出了一个俄罗斯方块游戏,最近看了看,今天在这篇文章里面我把我做的分析整理一下( ...

  6. PAT甲级——A1061 Dating

    Sherlock Holmes received a note with some strange strings: Let's date! 3485djDkxh4hhGE 2984akDfkkkkg ...

  7. 023-linux(2)

    1. head 查看文件的前N行 -n ,表示查看前几行 head - test.txt 2. tail 查看文件的后N行 -n,表示查看文件的后几行 tail - test.txt -f(循环读取) ...

  8. Dom4j官网解释实例

    Dom4j是一个易于使用的,开源的库,在Java平台上与XML,XPath,XSLT协同工作.使用Java集合框架,全面支持DOM,SAX,JAXP. 官方网站:http://dom4j.org 1. ...

  9. 如约而至(walk)

    LCA大佬的做法: 考虑暴力的高斯消元,我们优化它. $\sum\limits_{j} gcd(i,j)^{c-d} i^d j^d x_j=b_i$ $\sum\limits_{j} gcd(i,j ...

  10. 移动端“响应式布局”’--rem

    使用目的:为了让移动设计稿在大部分的移动设备上看起来有一致的展示效果,我们使用rem的像素单位. 方法一: 1.在页面引入js,获取屏幕大小,更新rem基准. (function () { var c ...