【发布时间】:2016-05-24 22:46:13
【问题描述】:
我为我的 MVC5 项目实现了一个自定义错误处理程序,如果它不是 customErrors 属性,一切都会好起来的。我将解释:当我在应用程序中遇到错误时,我会在 Global.asax 的 void Application_Error 中捕获它,如下所示:
protected void Application_Error(object sender, EventArgs e)
{
var httpContext = ((HttpApplication)sender).Context;
ExecuteErrorController(httpContext, Server.GetLastError());
}
public static void ExecuteErrorController(HttpContext httpContext, Exception exception)
{
if (!exception.Message.Contains("NotFound") && !exception.Message.Contains("ServerError"))
{
var routeData = new RouteData();
routeData.Values["area"] = "Administration";
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "Insert";
routeData.Values["exception"] = exception;
using (Controller controller = new ErrorController())
{
((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
}
}
}
然后,在我的 ErrorController 中执行以下操作:
public ActionResult Insert(Exception exception)
{
ErrorSignal.FromCurrentContext().Raise(exception);
Server.ClearError();
Response.Clear();
switch (Tools.GetHttpCode(exception)) // (int)HttpStatusCode.NotFound;
{
case 400:
return RedirectToAction("BadRequest");
case 401:
return RedirectToAction("Unauthorized");
case 403:
return RedirectToAction("Forbidden");
case 404:
return RedirectToAction("NotFound");
case 500:
return RedirectToAction("ServerError");
default:
return RedirectToAction("DefaultError");
}
}
public ActionResult Unauthorized()
{
return View();
}
...
所以第一次,一切正常 但 !!代码会重复,因为 NotFound 或 ServerError 页面不在 Shared 文件夹中。这些页面应该在 customErrors 属性中设置,但我根本不需要它。我终于得到了这个错误:ERR_TOO_MANY_REDIRECTS 因为那个。
我整天阅读以找到有关此的任何答案,并且似乎每个发布其代码的人都在使用与我相同的模式,并且无论我尝试什么,都没有任何效果。
注意我绝望的 if 条件:if (!exception.Message.Contains("NotFound") && !exception.Message.Contains("ServerError"))
我还在 global.asax 中评论了这两行,因为在我阅读的所有地方,它都说我们需要删除它们才能完成这项工作。
//GlobalConfiguration.Configure(WebApiConfig.Register);
//FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
另外,由于绝望的 if,我得到了这个答案:
Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed.
Details: To enable the details of this specific error message to be viewable on the local server machine, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "RemoteOnly". To enable the details to be viewable on remote machines, please set "mode" to "Off".
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="RemoteOnly"/>
</system.web>
</configuration>
我也试过Response.TrySkipIisCustomErrors = true;,还是不行!
那么,我怎样才能完全摆脱 customErrors 并在我的项目中管理我自己的错误处理程序?
【问题讨论】:
-
检查这个可能的答案:stackoverflow.com/questions/13905164/…
-
谢谢 RoteS。我阅读了每个答案,并找到了真正的答案。我会在几分钟内分享它。
标签: c# asp.net error-handling asp.net-mvc-5