• 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);
  • 相关阅读:
    深入理解HTTP Session
    java中使用队列:java.util.Queue
    throws/throw Exception 异常应用
    Log4j实现对Java日志的配置全攻略
    java中volatile关键字的含义
    hibernate调用oracle存储过程||函数
    手势仿QQ侧滑---秀清
    归档和解档---秀清
    全局定义UINavigationContoller--By秀清
    重力感应 加速计- By严焕培
  • 原文地址:https://www.cnblogs.com/hjworld/p/13605648.html
Copyright © 2020-2023  润新知