9

I joined this site today hoping someone would be kind enough to explain to me what i'm doing wrong with cookies in ASP.NET. I'm still learning so apoligies if my question is too basic, but i cannot find the answer on google. Every answer i find shows the code I already have.

I am experimenting with creating and reading cookies, i have put this code in my applications constructor. this is how i try to initialize my cookie and add it to the browser.

global.asax.cs

    public MyApplication()
    {
        myCookie = new HttpCookie("UserSettings");
        myCookie.Value = "nl";
        myCookie.Expires = DateTime.Now.AddDays(1d);
        Response.Cookies.Add(myCookie);
    }

a method in HomeController.cs (trying to read the cookie)

    public void setLang(string lang)
    {
        HttpCookie myCookie = Request.Cookies["UserSettings"];
        myCookie.Value = lang;
        //rest of method

I am getting an error at Response.Cookies.Add(myCookie); [HttpException (0x80004005): Response is not available in this context.]

My thought is that i might have forgot to import a namespace or something, but nothing i do seems to fix this error, can anyone point me in the right direction?

DeadManWalking
  • 227
  • 2
  • 4
  • 12
  • 2
    Please see answer to this question: http://stackoverflow.com/questions/1790457/global-asax-get-the-server-name – Paddy Jun 13 '12 at 08:10
  • I think that post is more about reading cookies from current context right? My error is at adding the cookie to the browser. – DeadManWalking Jun 13 '12 at 08:22
  • 1
    That post is about the fact that the Response object is not available at this point, in certain circumstances, which seems to be your issue. – Paddy Jun 13 '12 at 08:47
  • ah , now i have the answer i understand how that post was related to my error. – DeadManWalking Jun 13 '12 at 08:58

4 Answers4

21

You can't use the Global.asax constructor to add a cookie to the Response because the Global.asax constructor is called before the application starts processing the HTTP request.

Move your code from the Global.asax constructor to the Application_BeginRequest method:

public void Application_BeginRequest()
{
    myCookie = new HttpCookie("UserSettings");
    myCookie.Value = "nl";
    myCookie.Expires = DateTime.Now.AddDays(1d);
    Response.Cookies.Add(myCookie);
}

The Global.asax has a number of different events that are fired, you just chose wrongly.

  • Application_Init: Fires when the application initializes for the first time.
  • Application_Start: Fires the first time an application starts.
  • Session_Start: Fires the first time when a user’s session is started.
  • Application_BeginRequest: Fires each time a new request comes in.
  • Application_EndRequest: Fires when the request ends.
  • Application_AuthenticateRequest: Indicates that a request is ready to be authenticated.
  • Application_Error: Fires when an unhandled error occurs within the application.
  • Session_End: Fires whenever a single user Session ends or times out.
  • Application_End: Fires when the application ends or times out (Typically used for application cleanup logic).

(from http://en.wikipedia.org/wiki/Global.asax)

Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
Jaimal Chohan
  • 8,530
  • 6
  • 43
  • 64
  • is right here.i also test your code in application start event and getting same error but when you use it on Begin_Request it works – Sunny Jun 13 '12 at 08:42
  • 1
    This might also help you to better understand the .NET Web App lifecycle http://msdn.microsoft.com/en-us/library/bb470252.aspx#Stages – Jaimal Chohan Jun 13 '12 at 08:44
  • ah, very informative answer, i didn't know that. Your solution got rid of the error,so thanks! – DeadManWalking Jun 13 '12 at 08:47
  • Improve your answer by declaring `myCookie` and show also how to read a cookie without the need to scroll up to the question. Thanks. – Shadi Alnamrouti May 03 '17 at 09:12
0

cookies is a small piece of information stored on the client machine. This file is located on client machines.Its is used to store user preference information like Username, Password,City and PhoneNo etc on client machines. We need to import namespace called Systen.Web.HttpCookie before we use cookie.

Type of Cookies? Persist Cookie - A cookie has not have expired time Which is called as Persist Cookie

Non-Persist Cookie - A cookie has expired time Which is called as Non-Persist Cookie 

How to create a cookie?

Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie

    HttpCookie userInfo = new HttpCookie("userInfo");
    userInfo["UserName"] = "Jishan siddique";
    userInfo["UserColor"] = "Black";
    userInfo.Expires.Add(new TimeSpan(0, 1, 0));
    Response.Cookies.Add(userInfo);
jishan siddique
  • 1,848
  • 2
  • 12
  • 23
0

Cookie's common property:

1.Domain => Which is used to associate cookies to domain.

2.Secure  => We can enable secure cookie to set true(HTTPs).

3.Value    => We can manipulate individual cookie.

4.Values  => We can manipulate cookies with key/value pair.

5.Expires => Which is used to set expire date for the cookies. 

Advantages of Cookie:

1.Its clear text so user can able to read it.

2.We can store user preference information on the client machine.

3.Its easy way to maintain.

4.Fast accessing.

Disadvantages of Cookie

1.If user clear cookie information we can't get it back.

2.No security.

3.Each request will have cookie information with page. 

How to clear the cookie information?

1.we can clear cookie information from client machine on cookie folder

2.To set expires to cookie object userInfo.Expires = DateTime.Now.AddHours(1); It will clear the cookie with one hour duration

jishan siddique
  • 1,848
  • 2
  • 12
  • 23
-1

You can use predefined namespace in .Net. Like this:

System.Web.HttpContext.Current.Response.addCookie(cookieobject);
arghtype
  • 4,376
  • 11
  • 45
  • 60
jishan siddique
  • 1,848
  • 2
  • 12
  • 23