how do i save something in a cookie c# asp.net - c#

All i want to save instance of a class in a cookie just to check something.
Here is my code
class khurram {
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1;
}
but 'tcook' is not present. what am i doing wrong i don't understand.
i also tried
[serializable]
class khurram {
public string str1{get;set;};
}
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1;
please help.
thanks in advance

The Value property is defined to be of type string - in both of your examples, you appear to be trying to give it a class khurram
Someething like this may work better for you:
class khurram {
public string str1{get;set;};
}
// later ...
khurram k1= new khurram();
HttpCookie tcook = new HttpCookie("test");
tcook.Value = k1.str1;

HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;
// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);
// Add the cookie.
Response.Cookies.Add(myCookie);
Response.Write("<p> The cookie has been written.");

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.

How to initialize cookie in WebClient

In this question's most voted answer there is this line :
cookieJar.Add(new Cookie("my_cookie", "cookie_value", "/", "mysite"));
In this line, there are "my_cookie", cookie_value and "mysite" fields. I don't know how to fill these lines. Can you tell me how to fill those with an example? Thanks in advance.
Hope this Helps
CookieContainer gaCookies = new CookieContainer();
Uri target = new Uri("http://www.google.com/");
gaCookies.Add(new Cookie("__utmc", "#########") { Domain = target.Host });
or head here for more information
Try this:
HttpCookie _cookie = new HttpCookie("Department"); // Create and give name
_cookie.Expires = DateTime.Now.AddDays(30); // expries in one month
_cookie.Value = "Dep1"; // set value
HttpContext.Response.Cookies.Add(_cookie); // add cookie to the context

SetCookie seems to not working correctly

What I'm trying to do is set cookie to Response after some Validation on backend.
Here is my code:
Controller
public class MyController : Controller
{
public ActionResult Index()
{
var cookie = new HttpCookie("cookie-key", "true")
{
Expires = DateTime.Now.AddDays(30)
};
System.Web.HttpContext.Current.Response.SetCookie(cookie);
}
}
But after that in System.Web.HttpContext.Current.Request.Cookies there is no cookie with key "cookie-key".
I've added a <sessionState cookieless="UseCookies" /> to my web.config file but it's doesn't help.
How can I make it work as it should? Am I missing something?
Edit:
I've changed SetCookie to Cookies.Add but it doesn't helped.
Updated code:
public class MyController : Controller
{
public ActionResult Index()
{
var cookie = new HttpCookie("cookie-key", "true")
{
Expires = DateTime.Now.AddDays(30)
};
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
}
Try this code:
HttpCookie cookie = new HttpCookie("cookie-key","true");
cookie.Expires = DateTime.Now.AddDays(30);
cookie.Path = "/";
Response.Cookies.Add(cookie);
Response.SetCookie(cookie);
1) Probably you need write location(path)
2) Sometimes good do Cookies.Add AND SetCookies
SetCookie is for already existing Cookies.
You need to use Response.Cookies.Add(...)
That is all that is needed for your code to work.
Here is some code that I have in production that work 100%:
public ActionResult Login(string username, string password)
{
var userService = new UserService();
var loginResult = userService.ValidatePassword(username, password);
if (loginResult == null) return Redirect("/");
Response.Cookies.Add(new HttpCookie("tok", Uri.EscapeDataString(userService.CreateToken(loginResult)))
{
Expires = DateTime.Now.AddYears(1)
});
return Redirect("/admin");
}
Try this.
using System.Net;
var response = System.Web.HttpContext.Current.Response;
foreach( Cookie cook in response.Cookies)
{
// set your expiration here
cook.Expires = DateTime.MinValue;
}
Found reason why this doesn't work. It was error with javascript framework reactjs. There was 500 internal server error but because of ajax call couldn't diagnose this.
Thanks guys for answers :)

Change a cookie value of a cookie that already exists

I have a cookie called SurveyCookie. Created like so:
var cookie = new HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] = "1";
cookie.Values["surveyId"] = "1";
cookie.Values["surveyTitle"] = "Definietly not an NSA Survey....";
cookie.Values["lastVisit"] = DateTime.UtcNow.ToString();
cookie.Expires = DateTime.UtcNow.AddDays(30);
Response.Cookies.Add(cookie);
Which works great. Now the problem comes when I want to change the value "surveyPage" like so.
The below will create a new cookie which is not what I want.
int cookieValue = Convert.ToInt32(Request.Cookies["SurveyCookie"]["surveyPage"]) + 1;
Response.Cookies["SurveyCookie"]["surveyPage"] = cookieValue.ToString();
Then I tried this code below which doesn't work either. The surveyPage is still 1 when it should be 2.
Request.Cookies["SurveyCookie"]["surveyPage"] = cookieValue.ToString();
Since neither of the above works what does change the cookies value for surveyPage?
From ASP.NET Cookies Overview:
You cannot directly modify a cookie. Instead, changing a cookie
consists of creating a new cookie with new values and then sending the
cookie to the browser to overwrite the old version on the client.
You can try this:
HttpCookie cookie = Request.Cookies["SurveyCookie"];
if (cookie == null)
{
// no cookie found, create it
cookie = new HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] = "1";
cookie.Values["surveyId"] = "1";
cookie.Values["surveyTitle"] = "Definietly not an NSA Survey....";
cookie.Values["lastVisit"] = DateTime.UtcNow.ToString();
}
else
{
// update the cookie values
int newSurveyPage = int.Parse(cookie.Values["surveyPage"]) + 1;
cookie.Values["surveyPage"] = newSurveyPage.ToString();
}
// update the expiration timestamp
cookie.Expires = DateTime.UtcNow.AddDays(30);
// overwrite the cookie
Response.Cookies.Add(cookie);
You should always create a new cookie each time you need to modify an existing one , the following works for me :
var cookie = new System.Web.HttpCookie("SurveyCookie");
cookie.Values["surveyPage"] = newValue;
cookie.Expires = DateTime.Now.AddDays(1000);
cookie.SameSite = System.Web.SameSiteMode.None;
cookie.Secure = true;
this.HttpContext.Response.Cookies.Add(cookie);
Check out the Response.SetCookie() method as this will set update your existing cookie

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)
{
...
}

Categories

Resources