Sharing ASP.NET cookies across sub-domains

前端 未结 4 1946
野趣味
野趣味 2020-12-01 03:47

I have two sites, both on the same domain, but with different sub-domains.
site1.mydomain.com site2.mydomain.com

Once I\'m authenticated on each, I look at the c

4条回答
  •  北海茫月
    2020-12-01 04:28

    I've created a HttpContext extension method that will write a sub domain safe cookie.

    Blog post and discussion

    public static class HttpContextBaseExtenstions
    {
        public static void SetSubdomainSafeCookie(this HttpContextBase context, string name, string value)
        {
            var domain = String.Empty;
    
            if (context.Request.IsLocal)
            {
                var domainSegments = context.Request.Url.Host.Split('.');
                domain = "." + String.Join(".", domainSegments.Skip(1));
            }
            else
            {
                domain = context.Request.Url.Host;
            }
    
            var cookie = new HttpCookie(name, value)
            {
                Domain = domain
            };
    
            context.Response.SetCookie(cookie);
        }
    }
    
    // usage
    public class MyController : Controller
    {
        public ActionResult Index()
        {
            this.Context.SetSubdomainSafeCookie("id", Guid.NewGuid().ToString());
            return View();
        }
    }
    

提交回复
热议问题