Accessing Cookies in View value null MVC 4 - c#

So I really stumped with cookies right now and I'm not exactly sure whats going on. I saw a lot of cookie questions regarding losing values of cookies and I've tried almost copying exact same code but it still doesn't seem to resolve any of the issues.
Here is the code I use to set the cookie.
HttpCookie cookie = Response.Cookies["Name"];
if (cookie != null)
{
cookie.Value = user.LastName + " " + user.FirstName;
cookie.Expires = DateTime.UtcNow.AddYears(1);
Response.Cookies.Set(cookie);
}
else
{
cookie.Name = "Name";
cookie.Value = user.LastName + " " + user.FirstName;
cookie.Expires = DateTime.UtcNow.AddYears(1);
Response.Cookies.Add(cookie);
}
return RedirectToAction("Index", "Home");
Currently I'm debugging at Home/Index to check the values of the cookie before it gets to the view to see what is in the cookie.
One strange note is that when I check the content of the cookie the values are there but the Expire date is reset to 1/1/0001 right after I redirect from creating the cookie. I don't understand why does it reset it... or am I not setting/adding the cookies properly?
public ActionResult Index()
{
HttpCookie cookie = Request.Cookies["Name"];
ViewBag.Name = cookie.Value;
return View();
}
public ActionResult About()
{
HttpCookie cookie = Request.Cookies["Name"];
return View();
}
The issue is that the Cookie value is there before I return to the view but once I get to the view and try to access it directly from the view with.
#Response.Cookies["Name"].Value
The moment I get to the view the cookie values are null, expiration time gets change to when the browser is close when I check the cookie in the setting of chrome.
I read on some other articles it had something to do with the way I am redirecting, but I tried using response.redirect but it didn't seem to fix the issue. Can anyone point me in the right direction for handling this?

Related

Modifying cookie subkeys in C#

I can't for the life of me understand what I'm doing wrong here. I've searched high and low but everything I try doesn't seem to fix.
I'm trying to create a cookie that stores the first and last name of a user. If the user goes back and changes either the first or second name it should modify these subkeys in the userName cookie. This part doesn't seem to work though?
protected void btnContinue_Click(object sender, EventArgs e)
{
if (IsValid)
{
HttpCookie cookie = new HttpCookie("userName");
if (cookie != null)
{
Response.Cookies.Remove("userName");
cookie.Values["firstName"] = txtFirstName.Text;
cookie.Values["lastName"] = txtLastName.Text;
}
else
{
cookie.Values["firstName"] = txtFirstName.Text;
cookie.Values["lastName"] = txtLastName.Text;
}
cookie.Expires = DateTime.Now.AddMinutes(5);
Response.Cookies.Add(cookie);
}
Response.Redirect("~/Order.aspx");
}
The way to delete cookies on the client browser is to override them, setting the expires value to a date in the past.
When you use this code:
Response.Cookies.Remove("userName");
you only delete the cookie on server, which Means it's not sent to the client. This Means the old cookie on the client is kept.
To delete the old cookie:
HttpCookie cookie = new HttpCookie("olduserName");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
Here 'oldusername' contain the previous value of 'username'.
Edit:
Another way is to name your cookie with a name that doesn't change, ever, then you can simply override it with the new value, when username changes.
Edit2:
I actually made the same mistake as you did, you should use:
Response.Cookies.Set(cookie);
When using Add there can be more than one Cookie with the same name. This is most likely your problem (sorry, I did not see that before).
Edit2:
Just saw this line now:
Response.Redirect("~/Order.aspx");
You are redirecting! Then the cookies are not set on the client.
Instead you should set the cookies in "~/Order.aspx".

Shopping Cart Cookie not working in c# MVC

What this cookie aims is (if the cookie exists) to remember CartId so that user anonymous or registered can see his cart. If cookie doesn't exists it creates one with GuId and stores the cartId for some period of time.
I tried in some way to achieve that in this code:
enter image description here
And here cookie isn't working. It saves only cookie in line 190 with CartId always 0 and the other if and else statements are not checked. The line 190 I wrote it because it was throwing null exception statement without this line.Also I think that a mistake that I made is that I didn't use Current context above of line 197.
I tried to use HttpContext.Current and it throws this error :
enter image description here
Help me out please if it can be fixed. Any other example or url of cookies c# shopping cart is accepted. Thank you in advance.
First attempt:
public string GetCartId(HttpContextBase context )
{
if (context.Request.Cookies["CartId"] == null) return "0";
string cartId = context.Request.Cookies["CartId"].Value;
{
// if the cart ID doesn't exist in the cookie, generate
// a new ID
if (context.Request.Cookies["CartId"] == null)
{
// generate a new GUID
cartId = Guid.NewGuid().ToString();
// create the cookie object and set its value
HttpCookie cookie = new HttpCookie("CartId", cartId);
// set the cookie's expiration date
cookie.Expires = DateTime.Now.AddMinutes(2);
// set the cookie on the client's browser
context.Response.Cookies.Add(cookie);
// return the CartID
return cartId.ToString();
}
else // check if the cart ID exists as a cookie
{
// return the id
return cartId;
}
}
}
Here it saves cartId always null and not checking other statements
Second Attempt I added Current Context :
if (context.Request.Cookies["CartId"] == null)
{
HttpContext context = HttpContext.Current;
And context underlined with red says a local parameter named context cannot be declared in this scope because the name is used in an enclosing local scope.
Creating a cookies within a MVC Controller:
HttpCookie cookie = new HttpCookie("Cookie");
cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
Check & Read a cookie within a MVC Controller:
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
...
The Cookies.AllKeys.Contains() can replace your null check.
How to you call your method? What is the value of context?
The MSDN Documentation about Cookies can be found here...
Working with cookie in Legacy Asp.net was good, As you are developing application using MVC design pattern, Here we have other important concept to manage state.
Few are listed below:-
tempdata
viewdata
viewbag
And you can get explanation here
The value for the HttpOnly property of HttpCookie is "false" by default
This means you ask the browser to store your cookie on the disk
Change this to "true" before adding the cookie to the response. A note here, the client cookie will be lost if he closes all the instances of the browser.
If this does not help, you should add a privacy policy to your web site
try this, and if http only does not help, we can go for the p3p privacy policy solution

Lost session/cookie when login as another user

I am building dnn module which allow logged in user to log in as another user.
But I have some wired issue here.
This is how I log out current user and login as another user:
UserInfo userInfo = UserController.GetUserById(portalId, userId);
if (userInfo != null)
{
DataCache.ClearUserCache(this.PortalSettings.PortalId, Context.User.Identity.Name);
if (Session["super_userId"] == null)
{
Session["super_userId"] = this.UserId;
Session["super_username"] = this.UserInfo.Username;
}
HttpCookie impersonatorCookie = new HttpCookie("cookieName");
impersonatorCookie.Expires = DateTime.Now.AddHours(1);
Response.Cookies.Add(impersonatorCookie);
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
PortalSecurity objPortalSecurity = new PortalSecurity();
objPortalSecurity.SignOut();
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
Response.Redirect(Request.RawUrl, true);
}
And in PageLoad() I try to read value from this cookie but it doesn't read anything:
try
{
string super_userId = Request.Cookies["cookieName"]["super_userId"];
string super_username = Request.Cookies["cookieName"]["super_username"];
if (!String.IsNullOrEmpty(super_userId))
{
this.Visible = true;
this.lblSuperUsername.Text = Session["super_username"].ToString();
this.txtPassword.Enabled = true;
this.btnBackToMyAccount.Enabled = true;
}
...
I also have tried to do the same with session but nothing works, and I can't figure why?
As I find here, there can be problems with setting cookies in a request that gets redirected, and here is stated that cookies won't get set with a redirect when their domain is not /.
So you can try to not redirect using HTTP headers, but show a "Logged In" page instead that contains a "Home" link and a meta refresh or Javascript redirect.
By the way, setting a UserID in a cookie is not really the way to go. What if I change that cookie value to 1?
I suggest when you set a new cookie to always set the Domain, and probably and the Expires.
Response.Cookies[cookieName].Domain = RootURL;
Response.Cookies[cookieName].Expires = DateTime.UtcNow.AddDays(cDaysToKeep);
The domain is very importan to be the url with out the subdomain, eg only the mydomain.com with out the www. because if a cookie is set from www.mydomain.com and you try to read it from mydomain.com or vice versa, then the cookie will not be read and you may lost it / overwrite it.
So I suggest to make a function that when you set a cookie, you set at least 3 parametres, the Domain, the Expires, and the Value.
Similar questions and answers :
Multiple applications using same login database logging each other out
asp.net forms authentication logged out when logged into another instance
Put these two statements
Response.Cookies["cookieName"]["super_userId"] = this.UserId.ToString();
Response.Cookies["cookieName"]["super_username"] = this.UserInfo.Username;
after
UserController.UserLogin(portalId, userInfo, this.PortalSettings.PortalName, Request.UserHostAddress, false);
May be the UserLogin method is resetting the Session variables.
Hope it Helps :)

Delete cookie bug in IE?

I'm trying to delete some cookie which was set by javascript, it works well in Firefox and Chrome but not in IE, it deletes the cookie value in IE but not the file, so when I'm loading the page which uses cookie it loads some junk instead of nothing after delete.
I set the cookie like this
var exdate = new Date();
exdate.setDate(exdate.getDate() + 1);
var c_value = escape(data.d) + "; expires=" + exdate.toUTCString();
document.cookie = "user" + "=" + data.d;
and delete it like this
document.cookie = 'user=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
where is my problem?
I also have the code in C# for ASP.Net to delete the cookie, but it doesn't work in none of web browsers, (it works for cookie which was set by C# but not with Javascript) where is the problem with this code as well?
FormsAuthentication.SignOut();
Response.Cookies["user"].Expires = DateTime.Now.AddDays(-1);
Session.Clear();
Response.Cookies.Clear();
you must send cookie to the response stream otherwise your modification will never be committed to the browser.
I usually use this code to logout:
FormsAuthentication.SignOut();
CurrentContext.Session.Abandon();
HttpCookie c = CurrentContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (c != null)
{
c.Expires = DateTime.Now.AddDays(-1);
CurrentContext.Response.Cookies.Add(c);
}
While creating cookie Try to include domain name
Response.Cookies("abc").Domain = ".xyz.com"
and while deleting
Response.Cookies("uid").Value = Nothing
Response.Cookies("abc").Expires DateTime.Now.AddDays(-1)
Response.Cookies("abc").Domain = ".xyz.com"
and Check your cookies using below Tools
http://www.nirsoft.net/utils/iecookies.html

Why is my cookie not set?

I am playing around again with ASP.NET, and tried to set a cookie in one action which will be read in another action.
The strange thing is: the cookie gets set, but looses its value when accessing another page. Here is my simple controller code:
public class HomeController : Controller
{
public ActionResult About()
{
var cookie = Response.Cookies.Get("sid");
ViewData["debug"] = "Id: " + cookie.Value;
return View();
}
public ActionResult DoLogin()
{
var cookie = new HttpCookie("sid", Guid.NewGuid().ToString());
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
return RedirectToAction("About");
}
}
The flow is like this: first I access /Home/DoLogin, then I get redirected to /Home/About which should actually output the value of the sid cookie. But the cookie does not have any value.
Cookies are not disabled in my browser
I know that ASP.NET has its own session handling mechanism, just playing around and stumbled upon this cookie problem
Thanks for any hints!
In your About action, use Request.Cookies instead.
As a short explanation: When you set something in Response.Cookies, that cookie is sent to the client which stores it. On each subsequent Request to the same namespace, until the expiry date is reached, the client sends that cookie to the server, which stores it in Request.Cookies.

Categories