1

我正在尝试查看是否可以在 global.asax 的 Application_Error() 事件期间设置 cookie。

当我调试我的应用程序时,看起来代码添加了 cookie,但下次加载时,cookie 消失了。它每次都在重新创建cookie。我在本地(使用 casini)或服务器上尝试过。

我开始认为这是不可能的。

这是一些代码片段。

全球阿萨克斯

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
    }
}

导致错误的控制器

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

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

    return View();
}

更新 - 回答 Tejs 的评论 - 该项目的目标是通过电子邮件发送错误(很容易做到)。如果用户连续按 F5(我认为 cookie 可能是个好主意),我正在尝试找出一种方法来防止邮箱收到垃圾邮件。

更新 2 - 我已经改变了我的全局 asax 以反映更接近我想要完成的目标

4

2 回答 2

2

我个人使用 ErrorsContoller 来处理错误:

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");
    }
}

并在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));
}
于 2011-06-01T15:56:37.510 回答
1

叹息,原来我没有正确检查我的cookie。

我在做

HttpCookie exist = Response.Cookies[keyName];

代替

HttpCookie exist = Request.Cookies[keyName];
于 2011-06-02T21:59:59.623 回答