I have seen the persistent cookies examples in ASP.NET MVC C# here on stackoverflow.
But I can't figure out why the code below isn't working.
First I write to the cookie:
HttpCookie cookie = new HttpCookie("AdminPrintModule");
cookie.Expires = DateTime.Now.AddMonths(36);
cookie.Values.Add("PrinterSetting1", Request.QueryString["Printer1"]);
cookie.Values.Add("PrinterSetting2", Request.QueryString["Printer2"]);
cookie.Values.Add("PrinterSetting3", Request.QueryString["Printer3"]);
Response.Cookies.Add(cookie);
I see the cookies stored in Internet Explorer. The content looks OK.
Then the reading code:
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie.Values["PrinterSetting2"].ToString();
The cookie variable keeps null . Storing the PrinterSetting2 value in the test variable fails.
I don't know what I'm doing wrong because this is more or less a copy-paste from the examples here on stackoverflow. Why can't I read the PrinterSetting2 value from the cookie ?
try with below code :-
if (Request.Cookies["AdminPrintModule"] != null)
{
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie["PrinterSetting2"].ToString();
}
Have a look at this document http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/ :-
Below are few types to write and read cookies :-
Non-Persist Cookie - A cookie has expired time Which is called as
Non-Persist Cookie
How to create a cookie? Its really easy to create a cookie in the
Asp.Net with help of Response object or HttpCookie
Example 1:
HttpCookie userInfo = new HttpCookie("userInfo");
userInfo["UserName"] = "Annathurai";
userInfo["UserColor"] = "Black";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);
Example 2:
Response.Cookies["userName"].Value = "Annathurai";
Response.Cookies["userColor"].Value = "Black";
How to retrieve from cookie?
Its easy way to retrieve cookie value form cookes by help of Request
object. Example 1:
string User_Name = string.Empty;
string User_Color = string.Empty;
User_Name = Request.Cookies["userName"].Value;
User_Color = Request.Cookies["userColor"].Value;
Example 2:
string User_name = string.Empty;
string User_color = string.Empty;
HttpCookie reqCookies = Request.Cookies["userInfo"];
if (reqCookies != null)
{
User_name = reqCookies["UserName"].ToString();
User_color = reqCookies["UserColor"].ToString();
}
You must ensure that you have values in Request.QueryString.Just to check if your code works hard code values of cookies and then read from cookie.
Related
Codes below is to update value into existing cookie.
These codes working fine but now the I have no idea why it breaks and unable to update the latest value into cookie. (Cookie keep showing first assigned value).
Example flows:
a) The first assigned value in cookie is "abc".
b) Update "123" as latest value into cookie.
c) Read cookie but value remains "abc".
I have tried in Microsoft Edge where the cookie updates worked as expected but no idea why google chrome is failed to update cookie.
string m_cookie = FormsAuthentication.FormsCookieName;
string m_Json = string.Empty;
HttpCookie m_httpCookie;
FormsAuthenticationTicket m_ticket;
m_httpCookie = System.Web.HttpContext.Current.Request.Cookies[m_cookie];
m_ticket = FormsAuthentication.Decrypt(m_httpCookie.Value);
m_Json = (JsonConvert.SerializeObject(new UserCredential1
{
UserName = "123",
ExpiredAt = "123",
AccessToken = "123",
TokenType = "123",
})).ToString();
var newticket = new FormsAuthenticationTicket(m_ticket.Version, m_ticket.Name,
m_ticket.IssueDate, dtNowAdd1min, false, m_Json, m_ticket.CookiePath);
m_httpCookie.Value = FormsAuthentication.Encrypt(newticket);
if (newticket.IsPersistent) m_httpCookie.Expires = newticket.Expiration;
System.Web.HttpContext.Current.Response.Cookies.Set(m_httpCookie);
m_httpCookie = System.Web.HttpContext.Current.Request.Cookies[m_cookie];
m_ticket = FormsAuthentication.Decrypt(m_httpCookie.Value);
UserCredential result = JsonConvert.DeserializeObject<UserCredential>(m_ticket.UserData);
I'm suspecting this happens due to Google Chrome Samesite settings?
Anyone have idea about this? Thanks in advance.
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.
https://www.getpostman.com/docs/postman/sending_api_requests/cookies
above is the official document of how to add cookie in postman
I'm relatively new to C# and cookies but have used them extensively in VB. I've searched and tried many iterations of saving and retrieving cookies using methods from on this site and also on MSDN. My latest issue is an error being thrown telling me I can't convert a type cookie to a string. Below is the code I've used the create the cookie.
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["userGUID"] = userGUID;
myCookie.Expires = DateTime.Now.AddDays(2);
HttpContext.Current.Response.Cookies.Add(myCookie);
I've also tried:
HttpCookie myCookie = new HttpCookie("userGUID");
myCookie.Value = userGUID;
myCookie.Expires = DateTime.Now.AddDays(2);
HttpContext.Current.Response.Cookies.Add(myCookie);
Prior to using the line HttpContext.Current.Response.Cookies.Add(myCookie) the cookie wasn't even being saved.
The code I'm using the retrieve the cookie value is:
string userGUID = "";
if (HttpContext.Current.Request.Cookies["UserSettings"] != null)
{
if (HttpContext.Current.Request.Cookies["UserSettings"]["userGUID"] != null)
{
userGUID = HttpContext.Current.Request.Cookies["UserSettings"]["userGUID"];
}
}
I've also tried:
string userGUID = "";
if (HttpContext.Current.Request.Cookies["userGUID"] != null)
{
userGUID = HttpContext.Current.Request.Cookies["userGUID"];
}
Both approaches throw the same error:
Unable to cast object of type 'System.Web.HttpCookie' to type 'System.String'.
The above code resides in a .cs file - namespace TTS_CommonRoutines, class TTS_Common which inherits from System.Web.UI.Page.
At this point it's obvious to me that I must be missing something very simple but I just don't see it. Any help would be greatly appreciated.
Try this (FIX: HttpCookieCollection.Get: If the named cookie does not exist, this method creates a new cookie with that name)
// to send a cookie
var myCookie = Response.Cookies.Get("UserSettings");
myCookie.Values.Add("userGUID", System.Guid.NewGuid().ToString("N"));
myCookie.Expires = DateTime.Now.AddDays(2);
// to retrieve
var myCookie = Response.Cookies.Get("UserSettings");
var userGUID = myCookie.Values["userGUID"];
Try this:-
You need to fetch the cookies information into a HttpCookie reference variable because 'Request.Cookies' returns a HttpCookie object but you are trying to assign it to a string that is why you are getting this error. Once you retrieve it in a variable you can use it with its name (which returns string). Please check this MSDN documentation.
HttpCookie cookie = Request.Cookies["UserSettings"];
if(cookie != null)
{
userGUID = cookie["userGUID"];
}
I am trying to write cookie in ASP.NET using C# with this simple code:
HttpCookie cookie = new HttpCookie("UserToken");
cookie.Value = userToken.access_token; //string
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
Cookie was build. I am using Chrome browser but the value (Konten) always empty. What's the problem?
I also try to read this cookie with this code:
if (Request.Cookies["UserToken"] != null)
string userToken = Request.Cookies["UserToken"].Value;
"UserToken" cookie is not null but the value was empty string.
Thanks in advance
I am using cookies for my website.
I need to remove cookies immediately from browser for that i use this Code in C#
Code for removal of cookie
Response.Cookies["OptDepth"].Expires = DateTime.Now.AddYears(-30);
after execution of this code if i use this code
Code to check value of deleted cookie
Request.Cookies["OptDepth"].value;
then it gives me the value of specified cookie.
I need to remove cookies immediately from browser.
How can i do this.
If we change the name of that cookie with null then it works.
Code
Request.Cookies["OptDepth"].Name = null;
Now problem is solved.
Use Simple Code to replace cookies with expiry date:
if (Request.Cookies["OptDepth"] != null)
{
HttpCookie myCookie = new HttpCookie("OptDepth");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Here is an msdn detail link.Cookies
When adding a cookie ;
HttpCookie cookie = new HttpCookie("try");
cookie.Values["foo"] = "foo";
DateTime date = DateTime.Now.AddSeconds(-30);
cookie.Expires = date;
Response.Cookies.Add(cookie);
When Reading the cookie;
HttpCookie cookie = Request.Cookies["try"];
You will see the cookie is null.