API 读写cookie的方法

时间:2021-06-17 16:27:43   收藏:0   阅读:0
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;

namespace API.Cookie
{
    public class CookieInfo
    {
        public static readonly CookieInfo Instance = new CookieInfo();

        /// <summary>
        /// 生成Cookie
        /// </summary>
        /// <param name="value"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public CookieHeaderValue[] CookieSet(object value, HttpRequestMessage Request, bool b = true)
        {
            var json = JsonConvert.SerializeObject(value);
            string id = EncryptionAES.Instance.Encrypt(json);

            if (b)
            {
                #region 方法一

                var cookie = new CookieHeaderValue("session", id);
                cookie.Expires = DateTimeOffset.Now.AddDays(1);//不设置时间,浏览器关闭自动清除
                cookie.Domain = Request.RequestUri.Host;
                cookie.Path = "/";

                return new CookieHeaderValue[] { cookie };

                #endregion
            }
            else
            {
                #region 方法二

                var nv = new NameValueCollection();
                nv["sid"] = id;
                nv["token"] = "abcdef";
                nv["theme"] = "dark blue";

                var cookie = new CookieHeaderValue("session", nv);
                //cookie.Expires = DateTimeOffset.Now.AddDays(1);//不设置时间,浏览器关闭自动清除
                cookie.Domain = Request.RequestUri.Host;
                cookie.Path = "/";

                return new CookieHeaderValue[] { cookie };

                #endregion
            }
        }

        public string StaffNO { get; set; }
        public string UserName { get; set; }

        public void GetUserInfo(HttpRequestMessage Request)
        {
            string o = this.CookieGet(Request);
            string id = EncryptionAES.Instance.Decrypt(o);
            var u = JsonConvert.DeserializeObject<UserInfo>(id);
            //JsonConvert.DeserializeObject<List<PuchaseInfoLog>>(entity.txtPurchaseLog);
            if (u != null)
            {
                StaffNO = u.StaffNO;
                UserName = u.UserName;
            }
            else {
                StaffNO = "";
                UserName = "";
            }
           
        }

        /// <summary>
        /// 获取Cookie
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public string CookieGet(HttpRequestMessage Request, bool b = true)
        {
            //记录用户Code到Cookie中
            //HttpCookie coo = HttpContext.Current.Request.Cookies["session"];
            //if (coo == null)
            //{
            //    coo = new HttpCookie("session");
            //}
            //coo["User"] = null;// user.UserCode;
            //coo.Expires = DateTime.Now.AddDays(7.0);
            //HttpContext.Current.Request.Cookies.Remove("session");
            //HttpContext.Current.Request.Cookies.Add(coo);





            CookieHeaderValue cookie = Request.Headers.GetCookies("session").FirstOrDefault();
            if (b && cookie != null)
            {
                #region 方法一
                string session = "";

                if (cookie != null)
                {
                    session = cookie["session"].Value;
                }

                return session;

                #endregion
            }
            else if (!b && cookie != null)
            {
                #region 方法二
                string sessionId = "";
                string sessionToken = "";
                string theme = "";
                if (cookie != null)
                {
                    CookieState cookieState = cookie["session"];

                    sessionId = cookieState["sid"];
                    sessionToken = cookieState["token"];
                    theme = cookieState["theme"];
                }

                return sessionId;

                #endregion
            }

            return "";
        }

        /// <summary>
        /// 删除Cookie
        /// </summary>
        /// <returns></returns>
        public CookieHeaderValue[] DeleteCookie(HttpRequestMessage Request)
        {
            var cookie = new CookieHeaderValue("session", "");
            cookie.Expires = DateTimeOffset.Now.AddDays(-10);//不设置时间,浏览器关闭自动清除
            cookie.Domain = Request.RequestUri.Host;
            cookie.Path = "/";

            return new CookieHeaderValue[] { cookie };
        }


    }
}

 

 /// <summary>
        /// 用户登录生成cookie
        /// </summary>
        /// <param name="L"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PostLogin")]
        public HttpResponseMessage PostLogin(LoginInfo L)
        {
            var resp = new HttpResponseMessage();

            UserInfo u = new UserInfo();
            u = UserInfoAdapter.Instance.Login(L);

            if (u != null)
            {
                resp.Content = new StringContent(JsonConvert.SerializeObject("Success"), Encoding.GetEncoding("UTF-8"), "application/json");
                resp.Headers.AddCookies(CookieInfo.Instance.CookieSet(u, Request));
                return resp;
            }
            else
            {
                resp.Content = new StringContent(JsonConvert.SerializeObject("Failed"), Encoding.GetEncoding("UTF-8"), "application/json");
            }
            return resp;
        }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!