cant get cookie Values (NameValueCollection) - ASP.NET MVC - c#

I used belowe code to add cookie , I add some key, value in cookie ,
public static void AddCookie(this HttpContextBase httpContextBase, string cookieName, NameValueCollection cookieValues, DateTime expires, bool httpOnly = false)
{
var cookie = new HttpCookie(cookieName)
{
Expires = expires,
//Value = httpContextBase.Server.UrlEncode(value),// For Cookies and Unicode characters
HttpOnly = httpOnly
};
cookie.Values.Add(cookieValues);
//httpContextBase.Response.Cookies.Add(cookie);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
and fill keys like this :
NameValueCollection CookieValues = new NameValueCollection();
CookieValues.Add("pid", shoppingCartViewModel.ProductId.ToString());
CookieValues.Add("qty", "1");
HttpContext.AddCookie(shoppingCartCookiName, CookieValues, DateTime.Now.AddDays(1));
when I want read cookie , Values are null .
I used belowe code to check Cookie Value
public static NameValueCollection GetCookieValues(this HttpContextBase httpContext, string cookieName)
{
var cookie = System.Web.HttpContext.Current.Response.Cookies[cookieName];
if (cookie == null)
return null; //cookie doesn't exist
// For Cookies and Unicode characters
return cookie.Values;
}

You need to use Request.Cookies not Response.Cookies while reading the cookie.
Instead of
System.Web.HttpContext.Current.Response.Cookies[cookieName]
Use
System.Web.HttpContext.Current.Request.Cookies[cookieName]
In a web application the request is what comes from the browser and the response is what the server sends back. While reading cookie data from the browser you should use the Request.Cookies. When you are constructing cookies to be sent to the browser you need to add them to Response.Cookies.

Use this.
HttpCookie cookie = HttpContext.Request.Cookies.Get("name");

Related

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.

Unable to update cookies in asp.net mvc

I can write and read cookies but I can't change value for existing cookie it always has first set value. I found few ways how it can be implemented but no one works. Here is my code:
private void AddPost(string key)
{
var context = System.Web.HttpContext.Current;
var request = context.Request;
var response = context.Response;
var cookie = request.Cookies[Constants.PostsViewing];
if (cookie == null || string.IsNullOrEmpty(cookie.Value))
{
response.Cookies.Add(new HttpCookie(Constants.PostsViewing, key)
{
Expires = DateTime.Now.AddDays(365)
});
}
else
{
if (cookie.Value.Split(';').Contains(key))
{
return;
}
var v = cookie.Value + ";" + key;
cookie.Value = v;
cookie.Expires = DateTime.Now.AddDays(365);
response.Cookies.Add(cookie);
// this way also doesn't work
//cookie.Value = v;
//response.AppendCookie(cookie);
// and this
//response.Cookies[Constants.PostsViewing].Value = v;
//response.Cookies[Constants.PostsViewing].Expires = DateTime.Now.AddDays(365);
}
}
According to msdn cookie file should be owerwritten.
Each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will cause one to be overwritten.
Do you have any idea how to fix it?
I just ran into this exact scenario with a similar block of code:
public ActionResult Index(int requestValue)
{
var name = "testCookie";
var oldVal = Request.Cookies[name] != null ? Request.Cookies[name].Value : null;
var val = (!String.IsNullOrWhiteSpace(oldVal) ? oldVal + ";" : null) + requestValue.ToString();
var cookie = new HttpCookie(name, val)
{
HttpOnly = false,
Secure = false,
Expires = DateTime.Now.AddHours(1)
};
HttpContext.Response.Cookies.Set(cookie);
return Content("Cookie set.");
}
The first time that code would run, the cookie would be set without incident. But any subsequent run would never update it at all (value or expiration).
Turns out, the semi-colon is an illegal character in a cookie value, and trying to delimit your values with it will cause the cookie value to be truncated. If we change the semi-colon to another character, like a pipe (|), everything works out just fine.
Consider the header sent for a cookie value (courtesy of Fiddler):
Response sent 61 bytes of Cookie data:
Set-Cookie: testCookie=2;1; expires=Tue, 09-Sep-2014 19:23:43 GMT; path=/
As we can see, the semi-colon is being used to separate the individual parts of the cookie definition. Thus, if you want to use a semi-colon in cookie value itself, it must be encoded so as not to be misinterpreted. This answer gives a more detailed look into the actual specification: https://stackoverflow.com/a/1969339/143327.
You can't use a semi-colon, in plain text, as your delimiter.
According to the ancient Netscape cookie_spec:
This string is a sequence of characters excluding semi-colon, comma and white space.
You can't directly modify a cookie. Instead you are creating a new cookie to overrite the old one.
http://msdn.microsoft.com/en-us/library/vstudio/ms178194(v=vs.100).aspx
Try
var v = cookie.Value + ";" + key;
Response.Cookies[Constants.PostsViewing].Value = v;
Response.Cookies[Constants.PostsViewing].Expires = DateTime.Now.AddDays(365);
This should change the client Response instead of the servers Request.
In order to use Response.AppendCookie, you first have to get a HttpCookie from your Cookies collection.

C# persistent cookie

I have seen the persistent cookies examples in ASP.NET MVC C# here on stackoverflow.
But I can't figure out why the code below isn't working.
First I write to the cookie:
HttpCookie cookie = new HttpCookie("AdminPrintModule");
cookie.Expires = DateTime.Now.AddMonths(36);
cookie.Values.Add("PrinterSetting1", Request.QueryString["Printer1"]);
cookie.Values.Add("PrinterSetting2", Request.QueryString["Printer2"]);
cookie.Values.Add("PrinterSetting3", Request.QueryString["Printer3"]);
Response.Cookies.Add(cookie);
I see the cookies stored in Internet Explorer. The content looks OK.
Then the reading code:
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie.Values["PrinterSetting2"].ToString();
The cookie variable keeps null . Storing the PrinterSetting2 value in the test variable fails.
I don't know what I'm doing wrong because this is more or less a copy-paste from the examples here on stackoverflow. Why can't I read the PrinterSetting2 value from the cookie ?
try with below code :-
if (Request.Cookies["AdminPrintModule"] != null)
{
HttpCookie cookie = Request.Cookies["AdminPrintModule"];
test = cookie["PrinterSetting2"].ToString();
}
Have a look at this document http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/ :-
Below are few types to write and read cookies :-
Non-Persist Cookie - A cookie has expired time Which is called as
Non-Persist Cookie
How to create a cookie? Its really easy to create a cookie in the
Asp.Net with help of Response object or HttpCookie
Example 1:
HttpCookie userInfo = new HttpCookie("userInfo");
userInfo["UserName"] = "Annathurai";
userInfo["UserColor"] = "Black";
userInfo.Expires.Add(new TimeSpan(0, 1, 0));
Response.Cookies.Add(userInfo);
Example 2:
Response.Cookies["userName"].Value = "Annathurai";
Response.Cookies["userColor"].Value = "Black";
How to retrieve from cookie?
Its easy way to retrieve cookie value form cookes by help of Request
object. Example 1:
string User_Name = string.Empty;
string User_Color = string.Empty;
User_Name = Request.Cookies["userName"].Value;
User_Color = Request.Cookies["userColor"].Value;
Example 2:
string User_name = string.Empty;
string User_color = string.Empty;
HttpCookie reqCookies = Request.Cookies["userInfo"];
if (reqCookies != null)
{
User_name = reqCookies["UserName"].ToString();
User_color = reqCookies["UserColor"].ToString();
}
You must ensure that you have values in Request.QueryString.Just to check if your code works hard code values of cookies and then read from cookie.

Do I have to rewrite cookie everytime I postback to retain it?

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.

Problem with HttpOnly Cookies

I have a problem with creating HttpOnly Cookies , I use the following code to creat new cookie:
//A.aspx
HttpCookie ht = new HttpCookie("www");
ht.Value = "www";
ht.Name = "www";
ht.HttpOnly = true;
ht.Expires = DateTime.Now.AddDays(1);
Response.AppendCookie(ht);
Response.Redirect("B.aspx");
//B.aspx
HttpCookie cookie = Request.Cookies["Allowed"];
HttpCookie htt = Request.Cookies["www"];
if (cookie != null)
{
Response.Write(cookie.HttpOnly);
Response.Write(htt.HttpOnly);
}
else
{
cookie = new HttpCookie("Allowed");
cookie.HttpOnly = true;
cookie.Value = "ping";
cookie.Expires = DateTime.Now.AddMinutes(2);
Response.Cookies.Add(cookie);
Response.Write(cookie.HttpOnly);
Response.Write(htt.HttpOnly);
}
The problem is that the final result is always : False, although the HttpOnly property is set to True .
Can anyone explain me a way to figure this out ?
Thanx
Cookie parameters (expiration date, path, HttpOnly etc) are not sent back to the server by the browser, only the values. Sending them back would only introduce unnecessary bloat. Therefore the cookies in Request.Cookies will only contain the names and values.
If you want to see if your HttpOnly value is taking effect, use Firecookie or something similar to inspect the cookies. Or try accessing them in JavaScript - that's what it's supposed to prevent.

Categories