Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading/Writing Cookies

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?

like image 402
DeadManWalking Avatar asked Jun 13 '12 08:06

DeadManWalking


1 Answers

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)

like image 165
Jaimal Chohan Avatar answered Sep 22 '22 14:09

Jaimal Chohan