I have a situation where I want to use a cookie with these 2 subdomains app.example.com (ASP.NET) and appapi.example.com (Web API). I'm able to set the cookie successfully using the API like this:
public HttpResponseMessage Get()
{
...
var result = jsonHelper.setHttpResponseMessage(obj);
List<CookieHeaderValue> cookies = new List<CookieHeaderValue>();
NameValueCollection values = new NameValueCollection();
values["Value1"] = value1;
values["Value2"] = value2;
values["Value3"] = value3;
CookieHeaderValue cookie = new CookieHeaderValue("MyCookie", values);
/*#if DEBUG
cookie.Domain = Request.RequestUri.Host;
#else*/
cookie.Domain = ".example.com"; //I made this based on the answers to the questions posted below
//#endif
cookie.Path = "/";
cookie.Expires = DateTime.Now.AddHours(1);
cookie.HttpOnly = true;
cookies.Add(cookie);
result.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return result;
}
I'm using Postman and I get a response that looks like this under Cookie tab:
Name Value
MyCookie Value1=2&Value2=test&Value3=val
Then I'm sending the cookie to app.example.com/Page.aspx using Postman. The code at Page.aspx Page_Load looks like this:
if (!IsPostBack)
{
if (Request.Cookies["MyCookie"] != null)
{
var myCookie = Request.Cookies["MyCookie"].Values;
var value1 = myCookie["Value1"];
var value2 = myCookie["Value2"];
}
...
Here I'm not getting the values that I want which means that Request.Cookies["MyCookie"]
is null
I'm aware of this question and this one which I have implemented above, but still it didn't fix my issue.
Based on this, I believe that it's possible to use a cookie with 2 or more subdomains, so I need to know how to implement it properly.