我使用ASP.NET MVC和以下代码返回异常描述并将其存储在会话中。我需要帮助找出异常的错误代码,例如500
,403
,404
等。我该怎么做?
这就是我在会话中存储错误消息的方式:
System.Web.HttpContext.Current.Session["errorMessage"] = filterContext.Exception.Message.ToString();
public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
ProcessResult processResult = new ProcessResult();
// If the exception is already handled, we do nothing
if (filterContext.ExceptionHandled)
{
return;
}
else
{
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
processResult.Controller = controllerName;
processResult.Action = actionName;
processResult.ExceptionMessage = filterContext.Exception.Message;
System.Web.HttpContext.Current.Session["errorMessage"] = filterContext.Exception.Message.ToString();
processResult.StackTrace = filterContext.Exception.StackTrace;
processResult.Source = filterContext.Exception.Source;
}
// Mark the exception as handled
filterContext.ExceptionHandled = true;
}
答案 0 :(得分:9)
检查Exception是否是HttpException。然后按原样投射并获取状态代码。
if (filterContext.Exception is HttpException)
{
var statusCode = ((HttpException)filterContext.Exception).GetHttpCode();
}