Creating a Cookie in ASP.NET MVC - c#

This seems like it should be pretty straightforward. However, for the life of me, I can't seem to create a cookie in ASP.NET MVC. Currently, I have the following code:
DateTime lastActivityDate = DateTime.UtcNow;
if (Request.Browser.Cookies)
{
HttpCookie lastActivityCookie = new HttpCookie(COOKIE_LAST_ACTIVITY, lastActivityDate.ToShortDateString());
lastActivityCookie.Expires = DateTime.Now.AddMonths(-12);
this.ControllerContext.HttpContext.Response.Cookies.Add(lastActivityCookie);
}
I've set a breakpoint and noticed that the cookie appears to be getting added. (yes, I'm getting into the Request.Browser.Cookies block). I then attempt to retrieve the cookie using the following:
DateTime lastActivity = DateTime.UtcNow.AddDays(-7); // Default to the past week
HttpCookie lastActivityCookie = Request.Cookies[COOKIE_LAST_ACTIVITY];
if (lastActivityCookie != null)
{
DateTime temp = DateTime.UtcNow;
if (String.IsNullOrWhiteSpace(lastActivityCookie.Value) == false)
{
if (DateTime.TryParse(lastActivityCookie.Value, out temp))
lastActivity = temp;
}
}
Unfortunately, lastActivityCookie is always null. In addition, when I look in the "Resources" tab in Chrome, I see the cookies branch, however, the cookie I'm trying to create is not listed. There are two other cookies listed though, including the .ASPXAUTH cookie. What am I doing wrong?

Look at the Expires property of HttpCookie object - more on this here. I believe you shoud set cookie expiration date in future like in the example on msdn site. Because you set date time in the past the cookie automatically expires and you are never able to read it.

Related

.Net cookies keep coming back with expiration of zero

I am having trouble with the .Expires cookie attribute. It keeps coming back with 01/01/0001 12:00 AM, when I read the cookie back.
Here is the code. I added in the retrieve just below the save solely for debugging purposes. The save and retrieve happen in different places in the same file. I purposely did not specify a Domain, as I want the cookie to exist site wide.
The data shows up nicely, just not the expiration.
Note: I am testing under Visual Studio 2012 running under local host using .Net Framework 4.
System.Web.UI.Page oPage = this.Page;
HttpCookie oCookie = new HttpCookie("UserData");
// Set the cookie value.
oCookie.Secure = false;
oCookie["Field1"] = strField1;
oCookie["Field2"] = strField2;
oCookie.Expires = DateTime.Now.AddDays(1);
// Add the cookie.
oPage.Response.Cookies.Add(oCookie);
// Get the cookie.
oCookie = new HttpCookie("UserData");
oCookie = oPage.Request.Cookies["UserData"];
The browser will not send anything to the server except the cookie name and value. All of the other properties (expires, domain, path, httponly, ...) cannot be retrieved on requests after the cookie has been set.
The more accepted way to deal with this is to redirect the user to a login page when they try to access a protected resource and display some message along the lines of "You need to log in to view this page. If you were previously logged in, your session may have expired."
(Also note that you should be re-setting the cookie on every request, so that the user will not be logged out if they continue to use the site. It's not clear from your code whether you are doing this or not.)
I was just doing some more Google searching on my problem and saw this link, another posting here on Stackoverflow.
Cookies are always expired
I am also validating using the construct:
if (cookie != null && cookie.Expires > DateTime.Now)...
As several pointed out, expiration checking happens, if you can no longer retrieve the cookie. That is seriously dumb on whomever constructed this architecture. Yes, maybe there should be RequestCookie and ResponseCookie, the difference being ResponseCookie has no Expiry date.
The person who resopnded to me taught me that it is not just expires but other fields too.
In C# code, if using Form Authentication, You can find if cookie is persistent using below code
bool IsCookiePersistent = ((FormsIdentity)User.Identity).Ticket.IsPersistent;
Here Ticket will return the FormsAuthenticationTicket which has Expiration DateTime property.

how to remove cookies from browser in asp.net c#, SO answers NOT working

I'm trying to remove cookies using C# when a user logs out. The code suggestions listed here: remove cookies from browser do not work. I put several of them together in desperation and they are not working.
if (Request.Cookies["loginidcookie"] != null)
{
HttpCookie myCookie = new HttpCookie("loginidcookie");
myCookie.Value = String.Empty;
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Response.Cookies.Remove("loginidcookie");
}
Response.Redirect("logout.aspx");
So not only am I overwriting the value of the cookie with an empty string, I am setting it to expire yesterday AND removing it from the list of cookies. Yet when I run this code then hit the back button and reload, the cookie is still there with its original value. So how do I get rid of it?
Thank you
Try this instead:
string cookieName = "loginidcookie";
if (Request.Cookies[cookieName ] != null)
{
var myCookie = new HttpCookie(cookieName);
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
Response.Redirect("logout.aspx", false);
Note (from here):
You cannot directly delete a cookie on a user's computer. However, you
can direct the user's browser to delete the cookie by setting the
cookie's expiration date to a past date. The next time a user makes a
request to a page within the domain or path that set the cookie, the
browser will determine that the cookie has expired and remove it.
You are adding the Cookie and then Removing it from the collection before the response is sent so you are effectively doing nothing.
HttpCookie myCookie = new HttpCookie("loginidcookie");
... and then below
Response.Cookies.Add(myCookie);
Response.Cookies.Remove("loginidcookie");
If you change the cookie to expire yesterday, you need to leave the cookie in the collection so that the browser takes care of deleting it once it sees the cookie has been updated with an expiration date in the past. In other words, don't call Response.Cookies.Remove("loginidcookie");
Try RedFilter's solution but use Server.Transfer() or Server.TransferRequest() instead of Response.Redirect() which it seems doesn't always let those cookie responses happen due to a possible bug.
Are you checking the cookie after closing the browser? Or reloading the page in the same browser?
If you are opening the page in the same browser you will see the cookie which is expired, but if you opened the new browser and try to access the page again, you would not get the cookie.

How do Cookies Work in ASP.NET?

The website where I work is made up of several projects (written in several languages). Right now we have to use some awkward code in query strings and session variables to keep a person logged in when they go from project to project. Since cookies are domain specific we're trying to convert to them since they can be set in one project using one language yet be accessed by a different project (on the same domain) using a different language.
However I am having problems changing the value of a cookie and deleting them. Or to be more specific, I'm having trouble having any changes I make to a cookie stick.
For example in my logout code:
if (Request.Cookies["thisuserlogin"] != null)
{
HttpCookie myCookie = new HttpCookie("thisuserlogin");
myCookie.Value = String.Empty;
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Response.Cookies.Set(myCookie);
litTest.Text = myCookie.Expires.ToString() + "<br />" + Request.Cookies["thisuserlogin"].Expires.ToString();
}
I wind up with one line being yesterday and the next line being 1/1/0001 12:00:00 even though they SHOULD be the same cookie. So why is it that even though the cookie was set, it's value did not change? Is there a way to force the user's computer to update a cookie's value, including deletion?
Thank you very much.
PS Any URLs you can provide to give an easy-to-understand primer for cookies would be appreciated.
http://msdn.microsoft.com/en-us/library/ms178194(v=vs.100).aspx
if (Request.Cookies["thisuserlogin"] != null)
{
HttpCookie byeCookie = new HttpCookie("thisuserlogin");
byeCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(byeCookie);
// Update Client
Response.Redirect(Request.RawUrl);
}
You should use a tool like Fiddler on the client side to capture all of the data going back and forth. This will help you see that your cookie should be set with a date in the past (and missing from the next request too).
As for your textbox output, you're listing the cookie you created expire time and the expire time of the request cookie, which doesn't have one. If you were to look at the response cookie instead, you should see the date being set. Also, the call to Response.Cookies.Set is unnecessary. Response.Cookies.Add should be all you need.

First-Party Cookies Not Found On Same Web Server

I have two sites set up on one Windows 2008 IIS server. On the first site, the user hits the web page and the following simple C# code is used to create a cookie.
<%
HttpCookie myCookie = new HttpCookie("MyTestCookie");
myCookie.Value = "Hi";
myCookie.Expires = DateTime.Now.AddMinutes(1);
Response.Cookies.Add(myCookie);
>%
I've verified that this site can in fact "see" the cookie and I can use the following code to display its value:
<% Response.Write(Request.Cookies["MyTestCookie"].Value); %>
On the other site hosted on the exact same server. I use the following code to see if the cookie is assigned a value:
if (Request.Cookies["MyTestCookie"] == null)
{
lblErr.Text = "Cookie is null.";
}
else
{
lblErr.Text = Request.Cookies["MyTestCookie"].Value;
}
It's null. Just a few days before, however, it wasn't null. In the full code of the actual site, it was working for all but a few users. In trying to troubleshoot these particular users, it stopped working for everyone.
I don't know what I'm doing wrong, but I need to pass values between two sites which are completely independent and unaware of each other. I thought first-party cookies work fine if on the same server. What am I doing wrong?
Cookies are associated with the URL they come from - the browser would not send to site B the cookies received from site A (and vice-versa).
EDIT
If the problem is user-dependant maybe it is related to the cookie settings in the browser - if some user are blocking cookies for example.
Try setting the Path property to "/" and make sure the sites share the same domain name.
If they are on different sub domains, set the Domain property to domainname.com (your domain name).
Edit:
Your code should look like this:
if (Request.Cookies["MyTestCookie"] == null)
{
HttpCookie myCookie = new HttpCookie("MyTestCookie");
myCookie.Path = "/";
myCookie.Domain = "domain.com";
myCookie.Value = "Hi";
myCookie.Expires = DateTime.Now.AddMinutes(1);
Response.Cookies.Add(myCookie);
lblErr.Text = "Cookie was null.";
}
else
{
lblErr.Text = Request.Cookies["MyTestCookie"].Value;
}
The expiry time you set for the cookie (one minute from now) is a bit too short. Try setting it to 6 months in the future and see if that helps.

why does cookie.domain set two cookies?

I'm trying to get a subdomain to create a cookie for the entire domain instead of just its subdomian using the property cookie.domain, so the two subdomains can share the cookie info. When I deploy to IIS I get 2 cookies created, one for the domain and another for the subdomain. Why is that? When I update the cookie the only one that gets updated is the subdomain one, rendering the domain cookie kind of useless.
I tried to trace this through my code, but running visual studio in debug mode doesn't actually set any cookie at all, unless I don't set the cookie.domain property. Leaving domain.cookie out I get a cookie set to localhost, but only that one cookie. Any thoughts?
Okay, so I finally answered my own quesion(s). I'll tackle the second one first, about running the site in debug mode:
Visual studio debugs to the site http://localhost:[someport]. So if the code is set to create a cookie using cookie.domain for mydomain.com, the cookie isn't set because the browser knows you're at localhost instead of the domain specified. To remedy this I put an entry in my hosts file so that mydomain.com is pointed to 127.0.0.1. Then I fired up the site in debug mode. When the site came up as localhost I changed the URL in the browswer to http://subdomain.domain.com:[someport] and refreshed. Now the cookie can be set.
Doing this helped me trace through my code to find the issue of two cookies being created by my subdomain website. What I found is that the mydomain.com cookie was being created okay (CreateCookie method below) because of cookie.domain. However, when I was trying to update the expiration on the cookie (UpdateCookie below) it reverted back to thinking it should be using the subdomain cookie and went ahead and created it when it didn't find one. All I had to do was set cookie.domain again before setting the cookie and updating the expiration. Now I only have one cookie.
public void CreateCookie()
{
HttpCookie cookie = new HttpCookie(mConfig.webCookie);
TimeSpan span = new TimeSpan(0, 0, 30, 0);
DateTime time = DateTime.Now; ;
cookie["Username"] = mEncrypt.Encrypt(mUser.Username);
cookie.Domain = "mydomian.com";
cookie.Expires = time + span;
HttpContext.Current.Response.Cookies.Add(cookie);
}
public void UpdateCookie()
{
TimeSpan span = new TimeSpan(0, 0, 30, 0);
DateTime time = DateTime.Now;
HttpCookie cookie = HttpContext.Current.Request.Cookies[mConfig.webCookie];
// without specifying the domain the cookie will be set with the subdomain
cookie.Domain = "mydomain.com";
HttpContext.Current.Response.Cookies.Set(cookie);
HttpContext.Current.Response.Cookies[mConfig.webCookie].Expires = time + span;
}
You can set this cookie name for the full domain and subdomain on web.config on httpCookies
<httpCookies domain="domain.com" httpOnlyCookies="false" requireSSL="false" />
set domain.com and NOT www.domain.com to archive what you say, to have the same cookie on domain and sub domain. Similar there is a parameter on authentication that you set this cookie settings, depend for what cookie you talking about.
In your question "why is that?" the answer is that if you not set this parameters for the cookies then the cookies actually use the current host name, so they are different if the first name of the sub-domain change.

Categories

Resources