重庆熊猫 Loading

ASP.NET Core教程-Configuration(配置)-Cookie & Session

更新记录
转载请注明出处:
2022年11月3日 发布。
2022年11月1日 从笔记迁移到博客。

配置Cookie

获得Cookie对象

使用上下文Context 对象的属性 HttpRequest 对象和 HttpRespose 对象,获得Cookie对象。

使用 HttpContext.Request 获得 Cookie。

Console.WriteLine(this.HttpContext.Request.Cookies["key"]);

使用 HttpContext.Respose 获得 Cookie。

this.HttpContext.Response.Cookies.Append("Key", "Value");

Cookie的键值对配置

使用 CookieOptions 类型进行配置具体的键值对。

名称 描述
Domain This property specifies the hosts to which the browser will send the cookie. By default, the cookie will be sent only to the host that created the cookie.
Expires This property sets the expiry for the cookie.
HttpOnly When true, this property tells the browser not to include the cookie in requests made by JavaScript code.
IsEssential This property is used to indicate that a cookie is essential
MaxAge This property specifies the number of seconds until the cookie expires. Older browsers do not support cookies with this setting.
Path This property is used to set a URL path that must be present in the request before the cookie will be sent by the browser.
SameSite This property is used to specify whether the cookie should be included in cross-site requests. The values are Lax, Strict, and None (which is the default value).
Secure When true, this property tells the browser to send the cookie using HTTPS only.

获得Cookie对象的键值对

public string GetCookie()
{
    string cookieValue = this.HttpContext.Request.Cookies["Test"] ?? "0";
    return $"Count:{cookieValue}";
}

增加/修改Cookie对象的键值对

public string SetCookie()
{
    this.HttpContext.Response.Cookies.Append("Test", "0");
    return "Add Success";
}

删除Cookie对象的键值对

public string DeleteCookie()
{
    this.HttpContext.Response.Cookies.Delete("Test");
    return "Delete Cookie";
}

配置Session

Session中间件说明

Session中间件需要使用缓存中间件配合,即需要确定Session的数据到底存储在什么地方。支持的缓存中间件如下:

中间件 说明
AddDistributedMemoryCache 基于内存的缓存。This method sets up an in-memory cache. Despite the name, the cache is not distributed and is responsible only for storing data for the instance of the ASP.NET Core runtime where it is created.
AddDistributedSqlServerCache 基于SQLServer的缓存。This method sets up a cache that stores data in SQL Server and is available when the **Microsoft.Extensions.Caching.SqlServer ** package is installed.
AddStackExchangeRedisCache 基于Redis的缓存。This method sets up a Redis cache and is available when the Microsoft.Extensions. Caching.Redis package is installed.

配置Session服务和中间件

注册Session服务。下面使用基于服务器内存的缓存定义Session。

//先注册缓存中间件(基于内存)
builder.Services.AddDistributedMemoryCache();

//注册Session中间件
builder.Services.AddSession(options =>
{
    //设置过期时间(1小时)
    options.IdleTimeout = TimeSpan.FromHours(1);
    //设置必须使用Cookie
    options.Cookie.IsEssential = true;
});

在中间件配置中启用 Session 中间件。

app.UseAuthorization();
//使用Session中间件
app.UseSession();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

ISession 接口

通过 HttpContext 上下文对象获得 Session 实例。Session实例实现了 ISession 接口,支持以下方法:

方法 说明
Clear() This method removes all the data in the session.
CommitAsync() This asynchronous method commits changed session data to the cache.
GetString(key) This method retrieves a string value using the specified key.
GetInt32(key) This method retrieves an integer value using the specified key.
Id This property returns the unique identifier for the session.
IsAvailable This returns true when the session data has been loaded.
Keys This enumerates the keys for the session data items.
Remove(key) This method removes the value associated with the specified key.
SetString(key, val) This method stores a string using the specified key.
SetInt32(key, val) This method stores an integer using the specified key.

除了这些方法,可以使用扩展方法,自己进行扩展额外的功能方法。

在Controller中使用Session

检测 Session 是否可用

public string SessionIsAvaliable()
{
    if (this.HttpContext.Session.IsAvailable)
    {
        return "Avaliable";
    }
    else
    {
        return "Not Avaliable";
    }
}

获得 Session 键值对

public string GetSessionKeyValuePair()
{
    //先检测 Session 是否可用
    if(!this.HttpContext.Session.IsAvailable)
    {
        return "Session Not Avaliable";
    }

    //Session Id
    string sessionId = this.HttpContext.Session.Id;
    //Session Value
    string panda = this.HttpContext.Session.GetString("Panda") ?? "None";
    int dog = this.HttpContext.Session.GetInt32("Dog") ?? 0;

    //返回
    return $"Session Id: {sessionId},Panda:{panda},Dog:{dog}";
}

设置 Session 键值对

public string SetSessionKeyValuePair()
{
    //先检测 Session 是否可用
    if (!this.HttpContext.Session.IsAvailable)
    {
        return "Session Is Not Set";
    }

    this.HttpContext.Session.SetString("Panda", "666");
    this.HttpContext.Session.SetInt32("Dog", 222);
    this.HttpContext.Session.CommitAsync();
    return "Session Set Success";
}

移除 Session 键值对

public string RemoveSession()
{
    //检测Session是否可以使用
    if(!this.HttpContext.Session.IsAvailable)
    {
        return "Session Is Not Avaliable";
    }

    //先检测指定的Key是否存在
    if (!this.HttpContext.Session.Keys.Contains("Panda"))
    {
        return "Key:Panda Is Not Avaliable";
    }

    //然后移除指定Key
    this.HttpContext.Session.Remove("Panda");

    return "Remove Key: Panda Is Success";
}

清除 Session 键值对

public string ClearSession()
{
    //先检测Session是否可用
    if(!this.HttpContext.Session.IsAvailable)
    {
        return "Session Is Not Avaliable";
    }

    //清空Session
    this.HttpContext.Session.Clear();
    return "Clear Success";
}

获得 Session 所有 Key

public string GetAllSessionKeys()
{
    //先检测Session是否可用
    if (!this.HttpContext.Session.IsAvailable)
    {
        return "Session Is Not Avaliable";
    }

    if(this.HttpContext.Session.Keys.Count()<=0)
    {
        return "Session Is Not Contain Any Key";
    }

    StringBuilder resultString = new StringBuilder();
    foreach (string key in this.HttpContext.Session.Keys)
    {
        resultString.Append("Session Keys:");
        resultString.Append(key);
    }
    return resultString.ToString();
}
posted @ 2022-11-03 08:57  重庆熊猫  阅读(348)  评论(0编辑  收藏  举报