3分钟快速学会在ASP.NET Core MVC中如何使用Cookie

编程学习 2021-07-04 22:41www.dzhlxh.cn编程入门
这篇文章主要给大家介绍了关于如何通过3分钟快速学会在ASP.NET Core MVC中使用Cookie的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用ASP.NET具有一定的参考学习价值,需要的朋友们狼蚁网站SEO优化来一起学习学习吧

一.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源码发现它这个是可以做一些配置的。看狼蚁网站SEO优化的代码:

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";
   / 

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板