gpt4 book ai didi

asp.net-mvc-3 - MVC3错误处理-坚持使用名为 'Error'的View

转载 作者:行者123 更新时间:2023-12-03 07:48:10 27 4
gpt4 key购买 nike

我已经为我的应用程序定义了自定义错误处理,并且所有操作都非常出色-当找不到资源时,将呈现正确的“NotFound” View 。当发生未处理的异常时,将呈现“ServerError” View 。

我面临的问题是我的应用程序坚持尝试查找一个名为“错误”的 View ,但没有找到它,因为我没有一个 View ,因此在我的自定义错误处理例程中会抛出此异常:

“未找到 View 'Error'或其主 View ,或者 View 引擎不支持搜索的位置。已搜索以下位置:...“

我有一个Application_Error事件处理程序,它记录所有未处理的异常:

protected void Application_Error(Object sender, EventArgs e)
{
Exception lastEx = Server.GetLastError();

// Attempt to Log the error
try
{
Utils.Logger.Error(lastEx);
}
catch (Exception loggingEx)
{
// Try and write the original ex to the Trace
Utils.TryTrace(lastEx.Message);

// Try and write the logging exception to the Trace
Utils.TryTrace(loggingEx.Message);
}
}

我在web.config中将customErrors设置为“打开”:
<customErrors mode="On" defaultRedirect="blah">
<error statusCode="404" redirect="dee"/>
<error statusCode="500" redirect="blah"/>
</customErrors>

而且我在Global.asax.cs RegisterRoutes方法中定义了路由,这些路由对应于上面web.config中定义的Redirect:
routes.MapRoute(
"Error - 404",
"dee",
new { controller = "Error", action = "NotFound" }
);

routes.MapRoute(
"ServerError", // When this route is matched we want minimal error info displayed
"blah",
new { controller = "Error", action = "ServerError" }
);

我有一个BaseController,其中包含一个OnActionExecuted例程:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
Logger.Info(String.Format(Constants.LOG_ACTION_EXECUTED, filterContext.Controller.ToString(), filterContext.ActionDescriptor.ActionName));
// Log any exceptions
if (filterContext.Exception != null)
{
Stack<string> messages = new Stack<string>();
Exception current = filterContext.Exception;
messages.Push(current.Message);
while (current.InnerException != null)
{
messages.Push(current.InnerException.Message);
current = current.InnerException;
}
StringBuilder result = new StringBuilder();
while (messages.Count != 0)
{
result.Append(messages.Pop());
string nextline = messages.Count > 0 ? "OUTER EXCEPTION " + messages.Count + ": " : "";
result.Append(Environment.NewLine);
}
Logger.Error(result.ToString());
}
base.OnActionExecuted(filterContext);
}

框架是否还有其他地方定义了在发生未处理的异常时呈现哪个 View ?

我的自定义错误处理例程是否缺少最后一步,这将确保框架不再期望找到“错误” View ???

最佳答案

您需要在HandleErrorAttribute文件中删除Global.asax.cs处理程序。此属性将 View 设置为Error。然后,MVC运行时将不处理异常,并且异常将传播到Asp.Net运行时,在运行时它将使用customErrors部分显示页面。

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute()); // remove this line
}

关于asp.net-mvc-3 - MVC3错误处理-坚持使用名为 'Error'的View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8555911/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com