8/22/10

Instant Cookies

Look at the two methods shown below :

private void ModifyCookies()
{
HttpCookie objCookie = Request.Cookies["Cowboy"];
if (objCookie.Values.Get("position") == null) objCookie.Values.Add("position", "Receiver");
Response.Cookies.add(objCookie);
SetPlayerProperties();
}


private void SetPlayerProperties()
{
HttpCookie objCookie = Request.Cookies["Cowboy"];
Player objPlayer = new Player();
objPlayer.Positon = objCookie.Values.Get("position");
}

In the first method ModifyCookies() we get the cookie from the HttpRequest cookies collection. Let as assume the cookie was as follows:
//Cowboy = FirstName=Miles&LastName=Austin&Location=Dallas&Age=25

We then added another key/value pair to the cookie and the modified cookie now looks like :
Cowboy = FirstName=Miles&LastName=Austin&Location=Dallas&Age=25&position=Receiver

We then add the cookie to the HttpResponse cookies collection.

We then call the second method SetPlayerProperties() in which we access the new key that we have added to the cookie above.

NOTE : At this point the response has not been sent to the client yet, but we are still able to access the new key from the Request.Cookies collection.

The point to remember is (reference : Microsoft MSDN):

After you add a cookie to the HttpResponse.Cookies collection, the cookie is immediately available in the HttpRequest.Cookies collection, even if the response has not been sent to the client.

No comments: