Do I have to rewrite cookie everytime I postback to retain it? - c#

I don't really understand the difference between request cookie and response cookie. And it seem like everytime I postback, if I don't manually rewrite the cookie from request to response, then it disappears. How do I solve this?
public string getCookie(string name) {
if (Request.Cookies["MyApp"] != null && Request.Cookies["MyApp"][name] != null) {
return Request.Cookies["MyApp"][name];
} else if (Response.Cookies["MyApp"] != null && Response.Cookies["MyApp"][name] != null) {
return Response.Cookies["MyApp"][name];
} else {
return "";
}
}
public void writeCookie(string name, string value) {
Response.Cookies["MyApp"][name] = value;
HttpCookie newCookie = new HttpCookie(name, value);
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
}

Request.Cookies["MyApp"];
Code above will return you a cookie with name "MyApp" Doing this:
Request.Cookies["MyApp"][name]
You are taking value "name" from cookie called "MyApp".
But in your setCookie code you are setting a cookie with called name and do not create a cookie called "MyApp":
HttpCookie newCookie = new HttpCookie(name, value);
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
So, you should remove ["MyApp"] from any place you have it, or you may do something like this in setCookie:
public void writeCookie(string name, string value) {
if(Response.Cookies["MyApp"] == null) {
HttpCookie newCookie = new HttpCookie("MyApp");
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
}
if(Response.Cookies["MyApp"][name] == null)
Response.Cookies["MyApp"].Values.Add(name, value);
else
Response.Cookies["MyApp"][name] = val;
// or maybe simple Response.Cookies["MyApp"][name] = val; will work fine, not sure here
}

Request is the "thing" you get when the user tries to get to your website, while Response is a way of responding to this request.
In other words, see the official msdn documentation, namely this part:
ASP.NET includes two intrinsic cookie collections. The collection
accessed through the Cookies collection of HttpRequest contains
cookies transmitted by the client to the server in the Cookie header.
The collection accessed through the Cookies collection of HttpResponse
contains new cookies created on the server and transmitted to the
client in the Set-Cookie header.
http://msdn.microsoft.com/en-us/library/system.web.httprequest.cookies.aspx
So no, you don't have to create new cookies every time, unless they have already expired. Just be sure you reference the right collection of cookies.

You might want to check the domain and path that are being assigned to the cookie. It could be that your saved cookies are just being orphaned because the path is too specific or because the wrong domain is being set.
Domain is the server name that the browser sees such as "yourdomain.com". If the cookie is set with a different domain than this then the browser will never send it back. Likewise, the path of the cookie is the path to the resource being requested such as "/forum/admin/index" etc. The cookie is sent for that location and all child locations, but not for parent locations. A cookie set for "/forum/admin/index" will not be sent if you're accessing a page that sits in the "/forum" directory.

Related

Modifying cookie subkeys in C#

I can't for the life of me understand what I'm doing wrong here. I've searched high and low but everything I try doesn't seem to fix.
I'm trying to create a cookie that stores the first and last name of a user. If the user goes back and changes either the first or second name it should modify these subkeys in the userName cookie. This part doesn't seem to work though?
protected void btnContinue_Click(object sender, EventArgs e)
{
if (IsValid)
{
HttpCookie cookie = new HttpCookie("userName");
if (cookie != null)
{
Response.Cookies.Remove("userName");
cookie.Values["firstName"] = txtFirstName.Text;
cookie.Values["lastName"] = txtLastName.Text;
}
else
{
cookie.Values["firstName"] = txtFirstName.Text;
cookie.Values["lastName"] = txtLastName.Text;
}
cookie.Expires = DateTime.Now.AddMinutes(5);
Response.Cookies.Add(cookie);
}
Response.Redirect("~/Order.aspx");
}
The way to delete cookies on the client browser is to override them, setting the expires value to a date in the past.
When you use this code:
Response.Cookies.Remove("userName");
you only delete the cookie on server, which Means it's not sent to the client. This Means the old cookie on the client is kept.
To delete the old cookie:
HttpCookie cookie = new HttpCookie("olduserName");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
Here 'oldusername' contain the previous value of 'username'.
Edit:
Another way is to name your cookie with a name that doesn't change, ever, then you can simply override it with the new value, when username changes.
Edit2:
I actually made the same mistake as you did, you should use:
Response.Cookies.Set(cookie);
When using Add there can be more than one Cookie with the same name. This is most likely your problem (sorry, I did not see that before).
Edit2:
Just saw this line now:
Response.Redirect("~/Order.aspx");
You are redirecting! Then the cookies are not set on the client.
Instead you should set the cookies in "~/Order.aspx".

HttpListenerResponse adding a 2nd cookie makes all cookies disappear

I have the following code:
void WriteConnectionId(HttpListenerContext context, string id)
{
var cookie = context.Response.Cookies[CookieConnectionId];
if (cookie == null)
{
cookie = new Cookie(CookieConnectionId, id)
{
HttpOnly = true,
Secure = true,
Path = "/"
};
context.Response.Cookies.Add(cookie);
}
else
{
cookie.Value = id;
}
//context.Response.SetCookie(new Cookie("lalala", "lololo"));
}
This code stores correctly the cookie for "connection Id" in the client. In Chrome's console I can see the cookie in the list of cookies.
However, if I uncomment the last line that adds an extra cookie, then neither the session cookie or the dummy cookie make it to the client. They do not appear in Chrome's console.
Edit: removing the "/" path on the first cookie makes the first cookie appear, though with both values from the 1st and 2nd cookie concatenated with a comma.
Try
context.Response.AppendCookie(new Cookie("lalala", "lololo"));
I ended up fixing this issue by creating the following function:
void FlushCookie(HttpListenerContext context, Cookie cookie)
{
var builder = new StringBuilder();
builder.Append(cookie.Name);
builder.Append("=");
builder.Append(HttpUtility.HtmlAttributeEncode(cookie.Value));
builder.Append(";");
context.Response.Headers.Add(HttpResponseHeader.SetCookie, builder.ToString());
}
This can be modified further to add cookie expiration, path, etc.

Send Cookie in Post Response WebAPI

I am trying to send the user a cookie after I authenticate him. everything works perfect, the response is being constructed in my code, but even after the client got the response, There is no cookie saved in the browser (checking it via chrome F12 -> Resources).
Note: I can see the response being sent in fiddler with my cookie:
I wonder what is going wrong and why the browser doesn't save the cookie.
Here is the WebAPI function that handles the Post request:
public HttpResponseMessage Post([FromBody]User user)
{
IDal dal = new ProGamersDal();
var currentUser = dal.GetUser(user.Username, user.Password);
if (currentUser == null)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad request.");
}
else
{
var res = new HttpResponseMessage();
var cookie = new CookieHeaderValue("user",JsonConvert.SerializeObject(new ReponseUser(){username = currentUser.Username, role = currentUser.Role}));
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
res.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return res;
}
}
I've found out what the problem is since in Firefox the cookie was saved.
In chrome you cannot set a cookie with the domain of 'localhost' since it is considered as invalid domain (valid domain must contain two dots in it) - and therefore the cookie is invalid.
In order to solve it, in case of localhost, you should either:
set the domain to null.
set the domain to '' (empty)
set the domain to '127.0.0.1'
This is the fix in my code:
cookie.Domain = Request.RequestUri.Host == "localhost" ? null : Request.RequestUri.Host;

Lost session/cookie when login as another user

I am building dnn module which allow logged in user to log in as another user.
But I have some wired issue here.
This is how I log out current user and login as another user:
UserInfo userInfo = UserController.GetUserById(portalId, userId);
if (userInfo != null)
{
DataCache.ClearUserCache(this.PortalSettings.PortalId, Context.User.Identity.Name);
if (Session["super_userId"] == null)
{
Session["super_userId"] = this.UserId;
Session["super_username"] = this.UserInfo.Username;
}
HttpCookie impersonatorCookie = new HttpCookie("cookieName");
impersonatorCookie.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(impersonatorCookie);
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
PortalSecurity objPortalSecurity = new PortalSecurity();
objPortalSecurity.SignOut();
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
Response.Redirect(Request.RawUrl, true);
}
And in PageLoad() I try to read value from this cookie but it doesn't read anything:
try
{
string super_userId = Request.Cookies["cookieName"]["super_userId"];
string super_username = Request.Cookies["cookieName"]["super_username"];
if (!String.IsNullOrEmpty(super_userId))
{
this.Visible = true;
this.lblSuperUsername.Text = Session["super_username"].ToString();
this.txtPassword.Enabled = true;
this.btnBackToMyAccount.Enabled = true;
}
...
I also have tried to do the same with session but nothing works, and I can't figure why?
As I find here, there can be problems with setting cookies in a request that gets redirected, and here is stated that cookies won't get set with a redirect when their domain is not /.
So you can try to not redirect using HTTP headers, but show a "Logged In" page instead that contains a "Home" link and a meta refresh or Javascript redirect.
By the way, setting a UserID in a cookie is not really the way to go. What if I change that cookie value to 1?
I suggest when you set a new cookie to always set the Domain, and probably and the Expires.
Response.Cookies[cookieName].Domain = RootURL;
Response.Cookies[cookieName].Expires = DateTime.UtcNow.AddDays(cDaysToKeep);
The domain is very importan to be the url with out the subdomain, eg only the mydomain.com with out the www. because if a cookie is set from www.mydomain.com and you try to read it from mydomain.com or vice versa, then the cookie will not be read and you may lost it / overwrite it.
So I suggest to make a function that when you set a cookie, you set at least 3 parametres, the Domain, the Expires, and the Value.
Similar questions and answers :
Multiple applications using same login database logging each other out
asp.net forms authentication logged out when logged into another instance
Put these two statements
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
after
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
May be the UserLogin method is resetting the Session variables.
Hope it Helps :)

Cookies Do Not Set Quickly

I don't typically play with Cookies, but I wanted to look into this one verses the Session variables I typically use.
If I set a Cookie, then immediately try to read from it, I do not get the value back that I just set it to.
However, if I refresh the page or close the browser and open it back up, the Cookie appears to be set.
I'm debugging this in Chrome. Would that make any difference?
public const string COOKIE = "CompanyCookie1";
private const int TIMEOUT = 10;
private string Cookie1 {
get {
HttpCookie cookie = Request.Cookies[COOKIE];
if (cookie != null) {
TimeSpan span = (cookie.Expires - DateTime.Now);
if (span.Minutes < TIMEOUT) {
string value = cookie.Value;
if (!String.IsNullOrEmpty(value)) {
string[] split = value.Split('=');
return split[split.Length - 1];
}
return cookie.Value;
}
}
return null;
}
set {
HttpCookie cookie = new HttpCookie(COOKIE);
cookie[COOKIE] = value;
int minutes = String.IsNullOrEmpty(value) ? -1 : TIMEOUT;
cookie.Expires = DateTime.Now.AddMinutes(minutes);
Response.Cookies.Add(cookie);
}
}
Below is how I use it:
public Employee ActiveEmployee {
get {
string num = Request.QueryString["num"];
string empNum = String.IsNullOrEmpty(num) ? Cookie1 : num;
return GetActiveEmployee(empNum);
}
set {
Cookie1 = (value != null) ? value.Badge : null;
}
}
This is how I am calling it, where Request.QueryString["num"] returns NULL so that Cookie1 is being read from:
ActiveEmployee = new Employee() { Badge = "000000" };
Console.WriteLine(ActiveEmployee.Badge); // ActiveEmployee is NULL
...but reading from Cookie1 is returning null also.
Is there a command like Commit() that I need to call so that a cookie value is immediately available?
Cookies are not like Session- there are two cookie collections, not one.
Request.Cookies != Response.Cookies. The former is the set of cookies that are sent from the browser when they request the page, the latter is what you send back with the content. This is exposing the nature of the cookies RFC, unlike Session, which is a purely Microsoft construct.
When you set a cookie in a response it does not get magically transported into the request cookies collection. It's there in the response, you're free to check for it there, but it won't appear in the request object until it actually is sent from the browser in the next request.
To add to the other answers, you can get around the problem by caching the value in a private variable in case the cookie hasn't been updated yet:
private string _cookie1Value = null;
private string Cookie1 {
get {
if (_cookie1Value == null)
{
// insert current code
_cookie1Value = cookie.Value;
}
return _cookie1Value;
}
set {
// insert current code
_cookie1Value = value;
}
}
To simply put it; A cookie that is set in response, will only be available for the next htpp request (a next get or post action from the browser).
In detail: When a cookie value is set in HttpResponse, it will be persisted/stored only when after the response reaches client (meaning the browser will read the cookie value from Http Response header and save it). So, technically only for the henceforth requests it will be available. Example, when the user clicks on a link or a button that makes server call after this cycle from the browser.
Hope this gives you some idea, I suggest you read the What are cookies and ASP.NET wraps it before using it.

Categories