Skip to content

Instantly share code, notes, and snippets.

@blair55
Last active December 14, 2015 08:58
Show Gist options
  • Save blair55/5061052 to your computer and use it in GitHub Desktop.
Save blair55/5061052 to your computer and use it in GitHub Desktop.
HttpContext extension method to set sub domain safe cookie
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