Net Core 中WebAPI有关 Session的设置

原文地址:https://www.cnblogs.com/for-easy-fast/p/12157664.html

Net Core 中WebAPI有关 Session的设置,及获取
步骤一: 在Startup 文件中做相应的设置

ConfigureServices方法里添加

//ConfigureServices添加:

services.AddSession(options =>
{
options.Cookie.Name = ".AdventureWorks.Session";
options.IdleTimeout = System.TimeSpan.FromSeconds(120);//设置session的过期时间
options.Cookie.HttpOnly = true;//设置在浏览器不能通过js获得该cookie的值
});
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddHttpContextAccessor();
#region 跨域
services.AddCors(options =>
options.AddPolicy("AllowSameDomain",
builder => builder.WithOrigins().AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));
#endregion
//HttpContextAccessor 默认实现了它简化了访问HttpContext
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Configure方法里面添加

app.UseSession();//UseSession配置在UseMvc之前
二 在具体的Control配置相应数据

  1. 配置 并获取httpcontext

示例:

public class HomeController : Controller
{
private IHttpContextAccessor _accessor;
public HomeController(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public IActionResult Index()
{
var httpcontext = _accessor.HttpContext;
return View();
}
}

  1. 写SessionHelper类

    public class SessionHelper
    {
    private IHttpContextAccessor _accessor;

    private ISession _session ;
    private IRequestCookieCollection _requestCookie ;
    private IResponseCookies _responseCookie;
    public SessionHelper(HttpContext context)
    {
        _session = context.Session;
        _requestCookie = context.Request.Cookies;
        _responseCookie = context.Response.Cookies;
    }
    /// <summary>
    /// 设置session值
    /// </summary>
    /// <param name="session"></param>
    /// <param name="key">键</param>
    /// <param name="value">值</param>
    public  void SetSession(string key, string value)
    {
        var bytes = System.Text.Encoding.UTF8.GetBytes(value);
        _session.Set(key, bytes);
    }
    /// <summary>
    /// 获取Session值
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public  string GetSession(string key)
    {
        Byte[] bytes;
        _session.TryGetValue(key, out bytes);
        var value = System.Text.Encoding.UTF8.GetString(bytes);
    
        if (string.IsNullOrEmpty(value))
        {
            value = string.Empty;
        }
        return value;
    }
    ///// <summary>
    ///// 设置本地cookie
    ///// </summary>
    ///// <param name="key">键</param>
    ///// <param name="value">值</param>
    ///// <param name="minutes">过期时间</param>
    //public void SetCookies(string key,string value,int day = 1)
    //{
    //    _responseCookie.Append(key, value, new CookieOptions
    //    {
    //        Expires = DateTime.Now.AddDays(day)
    //    }) ;
    //}
    //public void  DeleteCookies(string key)
    //{
    //    _responseCookie.Delete(key);
    //}
    //public string GetCookiesValue(string key)
    //{
    //    _requestCookie.TryGetValue(key, out string value);
    //    if (string.IsNullOrEmpty(value))
    //    {
    //        value = string.Empty;
    //    }
    //    return value;
    //}
    

    }

  2. 方法里调用sessionHelper

                var httpContext = _accessor.HttpContext;
                SessionHelper session = new SessionHelper(httpContext);
                string key = "王明";
                string value = "2020年 大运年";
                //设置session值
                session.SetSession(key, value);
                //获取session值
                session.GetSession(key);
    
posted @ 2020-09-03 08:55  My*hj*world  阅读(1501)  评论(0编辑  收藏  举报

Copyright ©2017 侯健