Search code examples
c#asp.netasp.net-mvc-3cookiesapplication-error

Is it possible set cookies in Application_error


I'm trying to see if I can set a cookie during the Application_Error() event of the global.asax.

When I debug my application, it looks like the code adds the cookie but the next time it loads, the cookie is gone. It's recreating the cookie everytime. I tried it locally (using casini) or a a server.

I beginning to think it's not possible to do.

Here's some snippet of code.

global asax

protected void Application_Error()
{
    var ex = Server.GetLastError();
    Server.ClearError();
    string keyName = ex.StackTrace;
    string[] split = System.Text.RegularExpressions.Regex.Split(ex.StackTrace, "\r\n");

// Don't want the key name to be too long but unique enough
    if (split.Length > 0)
    {
        keyName = split[0];
    }

        keyName = keyName.Trim();

    HttpCookie exist = Response.Cookies[keyName];

    if (exist == null || string.IsNullOrWhiteSpace(exist.Value))
    {
        HttpCookie newCookie = new System.Web.HttpCookie(keyName, "ehllo");
        newCookie.Expires = DateTime.Now.AddYears(1);
        Response.Cookies.Add(newCookie);

        // email people
    }
}

Controller causing the error

public ActionResult Index()
{
    int a = 0;
    int b = 2;

    try
    {
        int hello = (b / a);
    }
    catch (Exception e)
    {
        throw;
    }

    return View();
}

Update - to answer Tejs's comment - The goal of the project will be to email the error (easy to do). I'm trying to figure out a way to prevent the mailbox from getting spammed if the user continuously pressing F5 (I though cookies might be a good idea).

update 2 - I've changed my global asax to reflect closer to what i'm trying to accomplish


Solution

  • Sigh, it turned out that I wasn't checking my cookie properly.

    I was doing

    HttpCookie exist = Response.Cookies[keyName];
    

    instead of

    HttpCookie exist = Request.Cookies[keyName];