Creating a Cookie and Setting it
Good Evening All
i have another Question. i have created a Function that creates a Cookie with a Domain like this
Code:
private static void SetCookieExtedend(String key, String value, String path)
{
DateTime expires = DateTime.UtcNow + TimeSpan.FromDays(2000);
bool secure = false;
String domain = "Ecash";
StringBuilder cookie = new StringBuilder();
cookie.Append(String.Concat(key, "=", value));
if (expires != null)
{
cookie.Append(String.Concat(";expires=", expires.ToString("R")));
}
if (!String.IsNullOrEmpty(path))
{
cookie.Append(String.Concat(";path=", path));
}
if (!String.IsNullOrEmpty(domain))
{
cookie.Append(String.Concat(";domain=", domain));
}
if (secure)
{
cookie.Append(";secure");
}
HtmlPage.Document.SetProperty("cookie", cookie.ToString());
}
and its working well , i have set the Cookie and it was stored as this
Quote:
UserID=142;expires=Mon, 14 Nov 2016 16:58:19 GMT;domain=Ecash
now i want to retrieve the Value of the Cookie and i have a function that does it like this
Code:
public static string GetCookie(string key)
{
string[] cookies = HtmlPage.Document.Cookies.Split(';');
key += '=';
foreach (string cookie in cookies)
{
string cookieStr = cookie.Trim();
if (cookieStr.StartsWith(key, StringComparison.OrdinalIgnoreCase))
{
string[] vals = cookieStr.Split('=');
if (vals.Length >= 2)
{
return vals[1];
}
return string.Empty;
}
}
return null;
}
the Following Line comes back with an empty String
Code:
string[] cookies = HtmlPage.Document.Cookies.Split(';');
Why ?
Thanks
Re: Creating a Cookie and Setting it
I don't know why that's empty, but why don't you use the cookie in the Response/Request?
Code:
//set cookie
HttpCookie cookie;
if (Request.Cookies["uid"] == null) {
cookie = new HttpCookie("uid");
cookie.Domain = "mydomain";
}
else {
cookie = context.Request.Cookies["uid"];
}
cookie.Expires = DateTime.Now.AddYears(30);
cookie.Value = "myvalue"; //set single value (user id in my example)
cookie.Values.Add("mykey", "myvalue"); //set multiple key in your example
Response.Cookies.Add(cookie);
//read the cookie
long user_id = 0;
if (Request.Cookies["uid"] != null) {
var cookie = Request.Cookies["uid"];
long.TryParse(cookie.Value, out user_id);
//or in your case, use cookie.Values
}