How to replace a HttpCookie in MVC3 - c#

The question is quite straightforward:
How to replace a HttpCookie in MVC3? (Assuming we have access to the HttpContext instance)

Use SetCookie
var cookie = Request.Cookies["cookieName"];
if (cookie != null)
{
cookie.Value = "new value";
Response.SetCookie(cookie);
}

Related

ASP.Net MVC 5 Cookie loses expiration upon return from the browser

This simple code has left me perplexed.
From this controller action method, I create a cookie , give it an expiration and set it to be HttpOnly. The cookie gets created correctly, added to the Response, looks correct on the browser debugger , however when returned back into the same code after refresh , loses expiration and HttpOnly flag. The cookie itself is still there , but the values are lost. If I watch Request.Cookies["mycookie"] back into the same controller/action method after a trip to the browser, the values are gone - the cookie itself is not deleted though.
If somebody understands this behaviour please explain, what might be happening here-
public class HomeController : Controller
{
public ActionResult Index()
{
if (this.ControllerContext.HttpContext.Request.Cookies["mycookie"] == null)
{
HttpCookie cookie = Response.Cookies["mycookie"];
cookie["mycookie"] = "test";
cookie.Expires = DateTime.Now.AddDays(90);
cookie.HttpOnly = true;
this.ControllerContext.HttpContext.Response.SetCookie(cookie);
}
return View();
}
The problem is this line: return View();
The cookie cannot be set and then read again (server-side) in the same round trip to the server. So, you need to create a second request for the cookie to be available. The simplest way is to force a second request by calling RedirectToAction, although you could use some clever AJAXy way of doing it so it appears to be the same request.
See this post for a working example - here is the part where the cookie is written and deleted.
public class CookieController : Controller
{
public ActionResult Create()
{
HttpCookie cookie = new HttpCookie("Cookie");
cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
return RedirectToAction("Index", "Home");
}
public ActionResult Remove()
{
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
cookie.Expires = DateTime.Now.AddDays(-1);
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
}
return RedirectToAction("Index", "Home");
}
}
Ashiquizzaman is also correct in that you are not setting the value of the cookie, but that is only half of the problem.
Please see this code below.
var request=this.ControllerContext.HttpContext.Request;
var response =this.ControllerContext.HttpContext.Response;
//OR
// var request=System.Web.HttpContext.Current.Request;
//var response =System.Web.HttpContext.Current.Response;
if (request.Cookies["mycookie"] == null)
{
HttpCookie cookie= new HttpCookie("mycookie");
cookie.Value = "test";//your problem hear.
cookie.Expires = DateTime.Now.AddDays(90);
cookie.HttpOnly = true;
response.Cookies.Add(cookie);
}
else//need to update your cookies then use this block or not
{
HttpCookie cookie=Request.Cookies["mycookie"];
cookie.Value = "test";//your problem hear.
cookie.Expires = DateTime.Now.AddDays(90);
cookie.HttpOnly = true;
//response.Cookies.SetCookie(cookie);
response.Cookies.Set(cookie);//To update a cookie, you need only to set the cookie again using the new values.
}
Hopefully it's help you.

Cookie reading value is null

I am using VS2015, C#.
My cookie value is:
Provider=Custom&Email=someemail#gmail.com&UserName=John&FirstName=Test&LastName=LastTest&Expires=11.7.2016
11:03:05
I am trying to get this value with:
HttpContext context = HttpContext.Current;
HttpCookie cookie = context.Request.Cookies["Login"];
string provider = cookie["Provider"];
string email = cookie["Email"];
both provider and email are null. How can I get values from cookie?
EDIT
Cookie is saved with:
HttpCookie cookie = new HttpCookie("Login");
cookie["Provider"] = "Custom";
cookie["Email"] = "test#gmail.com";
Response.Cookies.Add(cookie);
SECOND EDIT
I think the problem is encryption. I am using my own encrpytion mechanism. Cookie.value looks fine after decryption, but Cookie.Values is a little bit different than original. I think that's the problem.
Cookie.Value (before encryption): Provider=Custom&Email=test#gmail.com
Cookie.Value (after decryption): Provider=Custom&Email=test#gmail.com
Cookie.Values (before encryption) :{Provider=Custom&Email=test%40gmail.com}
Cookie.Value (after decryption - is different): {Provider%3dCustom%26Email%3dtest%40gmail.com}
Try below
HttpCookie cookie1 = Request.Cookies["Login"];
if (cookie1 != null)
{
string provider = cookie1["Provider"].ToString();
string email = cookie1["Email"].ToString();
}

Cookie missing when called in a class

Good day..! I have some issue getting the value of my cookie when called in a class..
here's my code in my default.aspx.. I can retrieve the value on the when inside the aspx page
HttpCookie myCookie = new HttpCookie("SAMPLE");
myCookie["value"] = HttpUtility.UrlEncode(value);
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);
if (Request.Cookies["SAMPLE"] != null)
{
string userSettings;
if (Request.Cookies["SAMPLE"]["value"] != null)
{ userSettings = Request.Cookies["SAMPLE"]["value"]; }
}
But when i called the cookie inside a class using this code HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["SAMPLE"]["value"]) it doesn't have any value.. Any idea..? Hope to hear from you soon..
Regards,
Link
You can replace with Response
....
Response.Cookies.Add(myCookie);
if (Response.Cookies["SAMPLE"] != null)
{
...
}

redirection between asp .net interfaces using cookies without querystring

I have two asp .net interfaces:
1. app1.domain.com
2. app2.domain.com
In default page of both, there is a link button from which we can switch between them. Previously we use query strings to pass username and password. But now we want to use cookies.
So in click event of link button, I have code like this:
HttpCookie cookie = new HttpCookie("MYCookie", Guid.NewGuid().ToString());
cookie.Domain = "domain.com";
cookie.Expires = DateTime.UtcNow.AddHours(1);
cookie.HttpOnly = false;
cookie.Secure = true;
cookie.Values.Add("Username", Username.ToString());
cookie.Values.Add("UserId", UserId.ToString());
Response.Cookies.Add(cookie);
Response.Redirect(destinationAddress);
Now, in default page of other application am reading cookie as:
protected override void InitializeCulture() {
if (Request.Cookies["MYCookie"] != null) {
HttpCookie cookie = null;
cookie = Request.Cookies.Get("MYCookie");
}
}
but here am finding Request.Cookies["MYCookie"] as null. Am i missing anything? Please advice.
It looks to me like the problem is your domain.
Change cookie.Domain = "domain"; to be cookie.Domain = ".domain.com";
I think you need to add HttpCookie same Path property for both app1 and app2
Response.Redirect generates ThreadAbortException.
All the changes made in your cookie will be lost. so you can use,
<meta http-equiv="Refresh" content="10; URL=your url" />
c# code:
System.Web.UI.HtmlControls.HtmlMeta meta = new System.Web.UI.HtmlControls.HtmlMeta();
meta.HttpEquiv = "Refresh";
meta.Content = "10; URL=your url";
Page.Header.Controls.Add(meta);
And set you cookie as like
cookie.Domain = ".domain.com";

Can't delete cookie in ASP.NET C#

I've got a logout.aspx that is called when the user clicks logout and there is where I want to delete the cookies but it just won't do it...
public partial class LogoutUser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie;
cookie = Request.Cookies.Get("Basket");
if (cookie == null)
{
cookie = new HttpCookie("Basket");
}
foreach (string item in cookie.Values.AllKeys)
{
Response.Cookies[item].Expires = DateTime.Now.AddDays(-1);
}
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies["Basket"].Expires = DateTime.Now.AddYears(-1);
Session.Abandon();
Response.Redirect("~/Default.aspx");
}
}
The cookie stores the values in the basket but after logging out I can still access the basket I don't know what's wrong.
Here is some relevant documentation.
I believe your mistake is in this line:
if (cookie == null)
You're checking for null, rather than checking for not null. Thus,
HttpCookie cookie;
cookie = Request.Cookies.Get("Basket");
if (cookie != null)
{
cookie = new HttpCookie("Basket");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
Response.Redirect("~/Default.aspx");
should do the trick.
Hope this is helpful.
Could it be this ?
Session identifiers for abandoned or expired sessions are recycled by default. That is, if a request is made that includes the session identifier for an expired or abandoned session, a new session is started using the same session identifier. You can disable this by setting regenerateExpiredSessionId attribute of the sessionState configuration element to true. For more information, see Session Identifiers.
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.abandon.aspx

Categories

Resources