TempData 的值会一直存在,直到它被读取或会话超时。以这种方式持久化 TempData 可以实现重定向等场景,因为 TempData 中的值在单个请求之外可用。
Dictionary<string, object> tempDataDictionary = HttpContext.Current.Session["__ControllerTempData"] as Dictionary<string, object>;
if (tempDataDictionary == null)
{
tempDataDictionary = new Dictionary<string, object>();
HttpContext.Current.Session["__ControllerTempData"] = tempDataDictionary;
}
tempDataDictionary.Add("LastError", Server.GetLastError());
然后在你的行动中你可以使用
var error = TempData["LastError"];
但这是其他解决方案,您无需重定向即可
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Response.Clear();
var httpException = exception as HttpException;
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
if (httpException == null)
{
routeData.Values.Add("action", "HttpError500");
}
else
{
switch (httpException.GetHttpCode())
{
case 404:
routeData.Values.Add("action", "HttpError404");
break;
default:
routeData.Values.Add("action", "HttpError500");
break;
}
}
routeData.Values.Add("error", exception);
Server.ClearError();
IController errorController = DependencyResolver.Current.GetService<ErrorController>();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
然后在控制器中你可以添加动作
public ActionResult HttpError500(Exception error)
{
return View();
}