Asp.NET cookies returning null - asp.net

I'm trying to save a cookie when a button is clicked like so...
protected void btn_login_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("test");
cookie["work"] = "now";
cookie.Expires = DateTime.Now + new TimeSpan(1, 0, 0, 0);
cookie.Domain = ".cookie.com";
Response.Cookies.Add(cookie);
}
Then on the page_load I am reading the cookie...
protected void Page_Load(object sender, EventArgs e)
{
string a = Response.Cookies["test"]["work"];
}
But it keeps coming back null. I am running this under localhost and I read that cookies won't save under localhost so I edited my host file to say
127.0.0.1 test.cookie.com
When I used Fiddler to see what was getting posted to the header of the page. It looks like this...
test/work = now
test =
So I can see that it is getting set but for some reason when I read it in it returns null.

On the page_load change it from Response.Cookies to Request.Cookies.
The Response object is for sending data back. The Request object has data that is passed to you.
example:
String a = Request.Cookies["test"]["work"];
Note that if the cookie doesn't exist, then this will cause a null reference exception.
Usually you should do something like:
protected void Page_Load(object sender, EventArgs e) {
HttpCookie cookie = Request.Cookies["test"];
String a = String.Empty;
if (cookie != null) {
a = cookie["work"];
}
}

Try this
Response.Cookies["work"].Value = "Value1"
Refer this for more information.
On pageload for reading the cookie try
string value = Request.Cookies["work"].Value

Related

Access Session object at Session_End Event in Globle.asax file

I want to access session variable at Session_End event of globle.asax file.But HtppContext.Current returns null. Please suggest any other way.
protected void Session_End(object sender, EventArgs e)
{
if (HttpContext.Current != null)
{
HttpContext ht = HttpContext.Current;
string username = ht.Session["UserName"].ToString();
}
}
I was facing the same problem yesterday, and I simply use:
string username = Session["UserName"].ToString();

Write Cookies and set cookies value as text box select Vlaue

I am trying to store the selected value of a dropdown list in a cookies which work perfectly with this code.
protected void state_DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie StudentCookies = new HttpCookie("userloaction_cookies");
StudentCookies.Value = state_DropDownList.SelectedValue;
StudentCookies.Expires = DateTime.Now.AddDays(1000);
Response.Cookies.Add(StudentCookies);
}
I then want to use the cookie value to set the select value for the dropdown list after page_load. It works, but I cannot change the dropdown value after the first value has been stored in the cookies.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["userloaction_cookies"] != null)
{
HttpCookie aCookie = Request.Cookies["userloaction_cookies"];
string cookiesvalue = Server.HtmlEncode(aCookie.Value);
state_DropDownList.SelectedValue = Server.HtmlEncode(aCookie.Value);
}
I think the issue is that the Page_load method triggers before the state_DropDownList_SelectedIndexChanged method.
Is there any possible way of making this work?
Page load triggers first on each post back.
You will need to check the value of IsPostBack.
Here is how:
if (!IsPostBack)
{
if (Request.Cookies["userloaction_cookies"] != null)
{
HttpCookie aCookie = Request.Cookies["userloaction_cookies"];
string cookiesvalue = Server.HtmlEncode(aCookie.Value);
state_DropDownList.SelectedValue = Server.HtmlEncode(aCookie.Value);
}
}

Putting Data from Cookie into a List<string> with ASP.net

I'm trying to make a shoppingcart using a cookie.
Every item has a Id which is put into the cookie.
Now I'm trying to put my cookie values into a List but I can't really find how to do it.
I want every value to be in a seperate index, is this possible?
Making the cookie:
HttpCookie myCookie = new HttpCookie("MyTestCookie");
Response.Cookies.Add(myCookie);
Adding a Id on buttonclick:
protected void Button1_Click(object sender, EventArgs e)
{
Request.Cookies["MyTestCookie"].Values.Add("", "3");
Response.Write(Request.Cookies["MyTestCookie"].Values.ToString());;
}
Try this
public void SetCookiesList(List<string> listOfCookies)
{
var req = HttpContext.Current.Request;
HttpCookie cookie = req.Cookies["cookieName"];
if (cookie != null)
{
var cookieVal = cookie.Value;
if (!string.IsNullOrEmpty(cookieVal))
listOfCookies.Add(cookieVal);
}
}

Cookie does not work in asp.net

I have two pages, test1.aspx and test2.aspx
test1.aspx has this
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("test", "test");
cookie.Expires = DateTime.Now.AddDays(1);
Response.SetCookie(cookie);
}
test2.aspx has this
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Response.Cookies["test"].Value);
}
The value of the cookie is null, no matter how many times I tried. I tried to open page1 and then page 2, expecting a cookie to work, but it is not working, I don't know why.
I think you need to read off the Request instead of the response.
As MSDN suggestions
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.Cookies["test"].Value);
}
In a web application, the request comes from the client (browser) and the response is sent from the server. When validating cookies or cookie data from the browser you should use the Request.Cookies collection. When you are constructing cookies to be sent to the browser you need to add them to the Response.Cookies collection.
Additional thoughts on the use of SetCookie
Interestingly for HttpResponse.SetCookie as used on your first page; MSDN says this method is not intended for use in your code.
This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
Even the example code found on this page uses the Response.Cookies.Add(MyCookie) approach and does not call SetCookie
You need is :
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.Cookies["test"].Value);
}
There is a sample here:
Reading and Writing Cookies in ASP.NET and C#
Regards
Save cookie with (response) and read cookie by (request)
//write
response.cookies("abc") = 123;
//read
if ((request.cookies("abc") != null)) {
string abc = request.cookies("abc");
}
Use Response.Cookies.Add(cookie);
Reference: http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cookies
On page test2.aspx
You should try this
protected void Page_Load(object sender, EventArgs e)
{
var httpCookie = Request.Cookies["test"];
if (httpCookie != null)
{
Response.Write(httpCookie.Value);
}
}

Accessing Sessions Variables in code behind

Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Session["Authenticated"] )
{
Response.Redirect( "index.aspx", false );
}
}
Once they login I set the session to true. Basically, if they don't have an active session I want them re-directed back to the index/login page. How do I accomplish this?
Use this check
if(Session["Authenticated"] == null || !(bool)Session["Authenticated"])
If you are using cookie, you can store a marker in your cookie so you can tell the difference between "fresh browser + new session" and "old browser + expired session".
Below is sample code that will redirect the user to an expired page if the session has expired.
void Session_OnStart(Object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
HttpCookieCollection cookies = context.Request.Cookies;
if (cookies["starttime"] == null) {
HttpCookie cookie = new HttpCookie("starttime", DateTime.Now.ToString());
cookie.Path = "/";
context.Response.Cookies.Add(cookie);
}
else {
context.Response.Redirect("expired.aspx");
}
}
And if you are trying to implement sessions this might help you http://aspalliance.com/1621_Implementing_a_Session_Timeout_Page_in_ASPNET.2

Resources