C# Cookie跨域实例

1)站点1,创建Cookie

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //设置Cookie
                HttpCookie myCookie = new HttpCookie("MyCook");//初使化并设置Cookie的名称
                DateTime dt = DateTime.Now;
                TimeSpan ts = new TimeSpan(0, 0, 1, 0, 0);//过期时间为1分钟
                myCookie.Expires = dt.Add(ts);//设置过期时间
                myCookie.Values.Add("LoginName", "Admin");
                Response.AppendCookie(myCookie);
            }
        }
        /// 
        /// 获取Cookie
        /// 
        /// 
        /// 
        protected void btnTestCookie_Click(object sender, EventArgs e)
        {
            HttpCookie myCookie = HttpContext.Current.Request.Cookies["MyCook"];
            if (myCookie != null)
            {
                string LoginName = myCookie["LoginName"];
            }
        }
    }
}
2)站点2,跨域获取Cookie

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie myCookie = HttpContext.Current.Request.Cookies["MyCook"];
            if (myCookie != null)
            {
                string LoginName = myCookie["LoginName"];
            }
        }
    }
}




你可能感兴趣的:(c#,web)