开发者

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'开发者_如何学Ct 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


Personally I use an ErrorsContoller to handle errors:

public class ErrorsController : Controller
{
    public ActionResult Fault(Exception ex)
    {
        var newCookie = new HttpCookie("key", "Exception Exists");
        newCookie.Expires = DateTime.Now.AddYears(Dfait.Environment.RemedyCacheDuration);
        Response.Cookies.Add(newCookie);

        // You could return a view or something here
        return Content("OOPS", "text/plain");
    }
}

and in Application_Error:

protected void Application_Error(object sender, EventArgs e)
{
    var app = (HttpApplication)sender;
    var context = app.Context;
    var ex = context.Server.GetLastError();
    context.Server.ClearError();

    var routeData = new RouteData();
    routeData.Values["controller"] = "Errors";
    routeData.Values["action"] = "Fault";
    routeData.Values["exception"] = ex;
    IController controller = new ErrorsController();
    controller.Execute(new RequestContext(new HttpContextWrapper(context), routeData));
}


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜