我想看看是否可以在global.asax.的Application_Error()事件期间设置cookie
当我调试应用程序时,看起来代码添加了cookie,但下次加载时,cookie就不见了。它每次都在重新制作饼干。我在本地(使用casini)或服务器上进行了尝试。
我开始觉得这是不可能的。
下面是一些代码片段。
全球asax
protected void Application_Error()
{
var ex = Server.GetLastError();
Server.ClearError();
string keyName = ex.StackTrace;
string[] split = System.Text.RegularExpressions.Regex.Split(ex.StackTrace, "rn");
// 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,以更接近我试图实现的
就我个人而言,我使用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));
}
唉,原来我没有正确检查我的cookie。
我在做
HttpCookie exist = Response.Cookies[keyName];
而不是
HttpCookie exist = Request.Cookies[keyName];