2

I'm trying to set and read cookies in c#. I wrote these two methods:

public static void setCookie(string sCookie, string value)
{
    HttpCookie cookie = HttpContext.Current.Request.Cookies[sCookie];
    if (cookie == null)
        cookie = new HttpCookie(sCookie);
    cookie.Value = value;
    cookie.Expires = DateTime.Now.AddYears(1);
    HttpContext.Current.Request.Cookies.Add(cookie);
}

public static string getCookie(string sCookie)
{
    if (HttpContext.Current.Request.Cookies[sCookie] == null)
        return null;
    return HttpContext.Current.Request.Cookies[sCookie].Value;
}

But I don't know why when I read the method getCookie, after calling setCookie, the collection HttpContext.Current.Request.Cookies contains always 2 elements, "__RequestVerificationToken" and "ASP.NET_SessionId", it doesn't contain my cookies...

Methods are not in any controller, just in a utils class, but I don't see any problem for that...

Can you figure out why my set method doesn't work? Thank you!

3
  • can u show how u set and get cookie.may be u are trying set and get a cookie in the same request Commented May 17, 2015 at 18:40
  • exactly you have to use response.cookies.add Commented May 17, 2015 at 18:41
  • I'm using cookies to set the current culture, i.e. "en" "it" "es" and so on. I could get the added cookie in the same request, but however I expect that in the next request cookie is surely present... I do use Response.Cookies.Add, as showed in my code, through HttpContext.Current.Request.Cookies.Add(cookie); Commented May 17, 2015 at 18:48

1 Answer 1

3

Set cookies to the Response object, also set the Path of a cookie

Sign up to request clarification or add additional context in comments.

3 Comments

I use HttpContext.Current.Request.Cookies.Add(cookie) if it is what you mean and the path is always "/" by default, and that's ok for me, I think
@RedPelle, please read the difference between Request and Response. It will make your life as a web developer much easier.
Changed the line HttpContext.Current.Request.Cookies.Add(cookie); with the line: HttpContext.Current.Response.Cookies.Add(cookie); Sometimes you can read the same thing for an hour without reading it right... I don't know why I was stuck with writing in the Request, that doesn't make any sense :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.