I am setting a cookie with:
HttpCookie cookie = new HttpCookie("simpleorder");
cookie.Expires = DateTime.Now.AddYears(1);
cookie["order"] = carModel.ToString();
cookie["price"] = price.ToString();
Response.Cookies.Add(cookie);
But when I check it a few seconds later it is expired and the expiration date is set to {01-01-0001 00:00:00}. I try to retrieve the code by
HttpCookie cookie = Request.Cookies["simpleorder"];
if (cookie != null && cookie.Expires > DateTime.Now)...
I don't clear the cookie any place, so I don't know why it expires?
This is common mis-understanding. The Request cookie collection represents the cookies included in the requests cookie header. Such cookies do not contain any info regarding when they expire. Strictly speaking .NET ought to have used two different types (RequestCookie and ResponseCookie) but instead chose to use the same type for both circumstances.
The Expires value only makes sense when adding cookies to the response.
At first I was also disappointed that request cookies don't have the Expires value, but after debugging using Fiddler2, I know that the http protocol does not include any Expires value for request cookies. The .NET Framework has no way of exposing Expires value for request cookies.
If you use Fiddler between your app and the browser, you can see the response cookie sent correctly to the browser with all properties. However, the request cookie in the http headers doesn't have the expires value, it only exposes cookie name and value. Browsers are required to send this request header, as specified in the http standard. The reason why could be to minimize size and web servers don't need to check anything other than the values.
So you do not need to check the expires value on web request, because it is what you set it to be on some earlier web response. If you receive the cookie back, that means the cookie is not yet expired. Once you set the expires value, the browser will handle the expiration. If you want to change the expires, just set the new value on the response.
Related
Is it possible to set Max Age for Cookies in Web Forms Application? I know, that it's okey to set Expire, but is there a way to set Max Age?
Asp.Net doesn't specifically provide this property on HttpCookie, probably because they are very Microsoft-centric, and IE doesn't support max-age (as least, as of IE11)
However, you can still do it. Here's some code demonstrating the proper and invalid ways to set this cookie with max-age:
// doesn't work:
var mytestcookie = new HttpCookie("regular_httpcookie", "01");
mytestcookie.Values.Add("max-age", "300");
Response.Cookies.Add(mytestcookie);
// *does* work:
Response.Headers.Add("set-cookie", "testingmaxage=01;max-age=300; path=/");
And it renders like this in the HTTP response:
Set-Cookie testingmaxage=01;max-age=300; path=/
X-AspNet-Version 4.0.30319
Set-Cookie regular_httpcookie=01&max-age=300; expires=Fri, 10-Jun-2016 15:02:15 GMT; path=/
As you can see above, if you are also setting cookies using HttpCookie, this will create a second "set-cookie" header on the response , but the browser won't mind, it will just add it to the list of cookies.
I tested on IE11 and Chrome and this is a non-issue - the cookies will all go in, as long as they have differing names. If the cookie name conflicts with one already set in HttpCookies, the last one in wins. Check out the text of your HTTP response to see which one goes in last. (Best to simply make sure they don't conflict though)
As I mentioned at the beginning, when testing on IE11, I noted that it's ignoring the max-age property of the cookie. Here's a link to a way to settle that issue:
Set-Cookie: Expire property, clock skew and Internet Explorer issue
I've ASP.NET MVC5 project with standard auth process.
After calling /Account/Login I've got response with new cookie .AspNet.ApplicationCookie with auth token. The question is how to get this token in Login action, right after it's generated?
My only idea is to try obtain it from response's cookie but it doesn't work:
// ... somwhere in login action
AuthenticationManager.SignIn(identity);
// <-- How to obtain auth token here? Code below don't work
var token = HttpContext.Current.GetOwinContext().Response.Cookies[".AspNet.ApplicationCookie"];
.. but this is not even compiling.
Request.Cookies[".AspNet.ApplicationCookie"]
Not sure if there is a leading period "." though, also try:
Request.Cookies["AspNet.ApplicationCookie"]
On callback action from OAuth you could use Request.Cookies[".AspNet.ExternalCookie"]
I believe you may be confusing Request and Response. Response is what you send TO the client - so you never want to read a cookie from there. Instead, read the cookie from the Request object.
If you "read" from the Response object and the cookie doesn't' already exist in it, it will simply create a NEW cookie of that name - with no value!
I have a problem with getting and sending this cookie header. To be more specific - with that MenuData cookie.
I'm sending GET request and with response i get this one particular cookie which I need to send back in next POST request.
The problem is that i get it in two parts(in cookiecontainer) and i have no idea how to Encode/Decode it to send it properly.
Here's the cookie header of POST i'm trying to send.
(//// - parts i need to put together)
Cookie:
//// MenuData={'Type':null;
ASP.NET_SessionId=oe5qzthlb51ri5nzxddadzzo;
.LoginISerwis=2880E262ECC48BD7D12443EDC97D9641E85401A345B629C2002AC89F22CEBD201700417EB0D499C6E8F10816AC1F457FF7CBD671C83509CEF405236C91D6CDD81543BF1EC507319EDD587E6FFDEBA80DFAD30D769DF6F70C942ABBCB383A0C0A0BF127F40FB4C04F25A6F68469EFAF51503EF10DCFF2F51A9B31040575B14962;
CustomerLogin=ID=xxxx&Login=xxxxx&RememberLogin=True;
//// 'Id':null}=
I need an advices how I can handle this kind of cookies.
Unfortunately, CookieContainer is known to have problems with parsing cookies with commas in them. My advice is to manually read the cookie header at this particular step and pass the cookie along to your next request.
I'm setting the forms authentication cookie like this below
FormsAuthentication.SetAuthCookie("test", true);
and when i check if its set it returns null...
Context.User.Identity.Name
any ideas why this is happening? thanks
You should always redirect after setting a forms authentication cookie:
public ActionResult SomeAction()
{
FormsAuthentication.SetAuthCookie("test", true);
return RedirectToAction("FooBar");
}
It's only in the subsequent action you are redirecting to that you will get the User.Identity.Name being properly initialized. The reason for that is pretty simple: the User.Identity.Name property is initialized from the Request cookies (a.k.a incoming cookies) whereas the FormsAuthentication.SetAuthCookie is setting the forms authentication to the response (a.k.a. emitting a cookie) so that on subsequent requests this cookie will be sent in the request.
Try to save them like this:
HttpCookie latcook = new HttpCookie("latitude", lat.Value.ToString());
HttpCookie lngcook = new HttpCookie("longitude", lng.Value.ToString());
Request.Cookies.Add(latcook);
Request.Cookies.Add(lngcook);
Everything has a value, and the code steps through without error.
Then immediately after those are set, I refresh my page and step through this:
HttpCookie latcook = Request.Cookies.Get("latitude");
HttpCookie lngcook = Request.Cookies.Get("longitude");
The latcook and lngcook variables have names, but no values. What am I doing wrong?
You are adding your cookies to the request object. They should be added to the response:
Response.Cookies.Add(latcook);
Response.Cookies.Add(lngcook);
Cookies added to the response are returned to the user's browser via a series of Set-Cookie HTTP headers. They are then subsequently sent back (upon the next request) via the Cookie HTTP header. (You should be able to watch this happen using Firebug, etc.) Ultimately, this header will be parsed and populate the Request.Cookies collection.