Problem saving/getting cookies in MVC 2 - c#

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.

Related

User Added Value to HttpContext Request/Response Header being removed

I am having some trouble adding a value to the Page.Request & Page.Response headers and have the key & value stay/persist through a redirect.
I have an enum tracking code that I want to place in the headers to trace how a user goes through my site prior to their checkout.
I am using this code to add the headers to response and request context.
var RequestSessionVariable = context.Request.Headers["SessionTrackingCode"];
if (RequestSessionVariable == null)
{
context.Response.AddHeader("SessionTrackingCode", ((int)tracker).ToString());
context.Request.Headers.Add("SessionTrackingCode", ((int)tracker).ToString());
}
else
{
if(!RequestSessionVariable.Contains(((int)tracker).ToString()))
{
RequestSessionVariable += ("," + ((int)tracker).ToString());
context.Request.Headers["SessionTrackingCode"] = RequestSessionVariable;
context.Response.Headers["SessionTrackingCode"] = RequestSessionVariable;
}
}
The method call that occurs in Page_Load of the necessary controls within the website:
trackingcodes.AddPageTrackingCode(TrackingCode.TrackingCodes.ShoppingCart, this.Context);
The header SessionTrackingCode is their but after a Response.Redirect("~/value.aspx") the RequestSessionVariable is always null. Is there something that happens on the redirect that will wipe out the headers that I add? Or what am I doing wrong on the addition of the header key and value?
this equals:
public partial class Cart : System.Web.UI.UserControl
Headers send by client on every request, so any redirect will require client to send headers again.
Unless you are using some special client (not a browser) any special headers will be essentially ignored/lost during requests. Browser only will send known headers (cookies, authentication, referrer) in requests and act on other set of known headers in response (setCookies). You are using custom header that not known to browser so browser will not read in from response nor send it in request.
Your options:
switch to use cookies for your tracking (same as everyone else)
use AJAX requests to send/receive custom headers (probably not what you are looking for as urls look like regular GET/POST ones)
build custom client that will pay attention to your headers (purely theoretical, unless you building some sort of sales terminal no one will install your client to visit your site)
Note: adding headers to request in page code does no make much sense as request will not be send anywhere (it is what come from browser).
This looks like a job for cookies, rather than http headers. The browser will not return your custom headers to you, but it will return your cookies.

Cookie with value separated by comma

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.

What domain should I give this cookie?

I'm trying to call a web service from a c# application, with sessionID.
In order to do this I need to set the "Domain" header in a cookie.
In Fiddler it looks like - "ASP.NET_SessionId=izdtd4tbzczsa3nlt5ujrbf5" (no domain is specified in the cookie).
The web service is at - "http://[some ip goes here]:8989/MyAPI.asmx".
I've tried:
http://[ip] ,
http://[ip]:8989 ,
http://[ip]:8989/MyAPI.asmx
All of these cause runtime error.
I've also tried the ip alone (i.e. 100.10.10.10) , which doesn't cause a runtime error, and sets the cookie, but the cookie is never sent when I invoke a web method.
Here's my code for setting the domain:
if (!string.IsNullOrEmpty(currentSessionID))
{
req.CookieContainer=new CookieContainer();
Cookie cookie = new Cookie("ASP.NET_SessionId", currentSessionID);
cookie.Domain = GetCookieUrl(); //<- What should this be?
req.CookieContainer.Add(cookie);
}
So what should the domain be?
Thanks.
I believe it should simply be [ip]. Drop the http:// part of what you've tried.
According to this page on MSDN, your code should be
cookie.Domain = "100.10.10.10";
Next, exactly what error are you getting? Also, are you confusing a Compile error with a Runtime error? I find it hard to believe you are getting a compilation error as Domain is a String property which means you can put pretty much anything into it.
Finally, why are you sending a cookie to a web service? The normal way is to pass everything in the form post or on the query string.
Update
BTW, if you absolutely must add a cookie to the header in order to pass it to a web service, the way you do this is (taken from here):
byte[] buffer = Encoding.ASCII.GetBytes("fareId=123456"); //the data you want to send to the web service
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;
WebReq.Headers["Cookie"] = "ASP.NET_SessionId=izdtd4tbzczsa3nlt5ujrbf5"
Stream PostData = WebReq.GetRequestStream();
Note that this sets the header inline with the request without instantiating a "cookie" object. The Domain property of a cookie is to help ensure the cookie is only sent to the domain listed. However, if you are initiating the request and trying to append a cookie to it, then the best way is to just add it as a string to the request headers.
The reason the cookie was not sent is that the request's content length should be set after adding the cookie, and not before.
The domain is the ip alone.
// Simple function to get cookie domain
private string GetCookieDomain(string uri)
{
Uri req_uri = new Uri(uri);
return req_uri.GetComponents(UriComponents.Host, UriFormat.Unescaped);
}

Retrieving cookies from HttpResponse

I have a controller action that I call via Ajax in which I set a cookie like this:
Response.Cookies["Notifications"].Value = "false";
Response.Cookies["Notifications"].Expires = DateTime.Now.AddYears(1);
In another controller action I am checking for this cookie like this:
if(Request.Cookies["Notifications"] != null &&
Request.Cookies["Notifications"].Value =="false")
//Do something here
The problem is that Request.Cookies["Notifications"] is always null. I have verified that the cookie is getting set via FireBug. I'm testing this via visual studio's web built in web server.
The problem was with the fact that I was also setting this:
Response.Cookies["Notifications"].Secure = true;
And of course the cookie isn't being sent because I'm not using Https.
When in FireBug do you see the cookie sent back in the request? Also you can have a look at raw request to see if it is actually there
Just an idea/advice... You could fire Fiddler to sniff the actual http traffic and see how and if the cookies are being transferred in the http headers

Cookies are always expired

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.

Categories

Resources