Last active
December 14, 2015 08:58
-
-
Save blair55/5061052 to your computer and use it in GitHub Desktop.
HttpContext extension method to set sub domain safe cookie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
if(!String.IsNullOrEmpty(domain) | |
{ | |
cookie.Domain = domain | |
} | |
context.Response.SetCookie(cookie); | |
} | |
} | |
// usage | |
public class MyController : Controller | |
{ | |
public ActionResult Index() | |
{ | |
Context.SetSubdomainSafeCookie("id", Guid.NewGuid().ToString()); | |
return View(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment