5

我有一个即将发布的 MVC 2 Web 应用程序。到目前为止,我已经关闭了自定义错误,但我希望它们在我准备好生产时工作。

我已经使用以下内容设置了我的 web.config:

<customErrors mode="On" defaultRedirect="/Error/">
  <error statusCode="404" redirect="/Error/NotFound "/>
</customErrors>

404 完美运行,NotFound 是一个直接映射到视图的操作,该视图使用我自己的 Site.Master 文件显示一个非常标准的 404 页面。

对于 404 以外的任何内容,我希望用户能够查看异常详细信息。(这是一个内部应用程序,这样做没有安全风险)。

Error默认操作Index设置为返回我定义的 View() 。我想不通的是如何将异常信息传递到视图中?

这看起来很有希望:

http://devstuffs.wordpress.com/2010/12/12/how-to-use-customerrors-in-asp-net-mvc-2/

但是当我使用 View 时:

<%@ Page Title="" Language="C#" 
    MasterPageFile="~/Views/Shared/Bootstrap.Master"
    Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>

错误页面本身会引发错误,因为 HandleErrorInfo 为空。显然,自定义错误中的错误会导致 MVC2 出现一系列问题,结果是黄屏死机。

我想要么我错过了博客中的一些关键内容,要么它没有解释如何在不为我的每个控制器/操作设置 Error 属性的情况下让 HandleErrorInfo 为 null 以外的任何内容。

另外,我知道 MVC3 可以更好地处理这个问题,并且我知道 Razor 非常好。它没有用于这个项目,也不会改变这个项目来使用它。所以请不要“使用 MVC3”的答案。

4

1 回答 1

12

为空,HandleErrorInfo因为您正在执行重定向customErrors

这是我在我的最新项目中尝试的想法,我为 MVC 2 进行了更新。我没有使用customErrors,因为我无法在不执行重定向的情况下调用控制器操作(我猜)。

应用程序错误

protected void Application_Error(Object sender, EventArgs e)
{
    GlobalErrorHandler.HandleError(((HttpApplication)sender).Context, Server.GetLastError(), new ErrorController());
}

全局错误处理程序

public class GlobalErrorHandler
{
    public static void HandleError(HttpContext context, Exception ex, Controller controller)
    {
        LogException(ex);

        context.Response.StatusCode = GetStatusCode(ex);
        context.ClearError();
        context.Response.Clear();
        context.Response.TrySkipIisCustomErrors = true;

        if (IsAjaxRequest(context.Request))
        {
            ReturnErrorJson(context, ex);
            return;
        }

        ReturnErrorView(context, ex, controller);
    }

    public static void LogException(Exception ex)
    {
        // log the exception
    }

    private static void ReturnErrorView(HttpContext context, Exception ex, Controller controller)
    {
        var routeData = new RouteData();
        routeData.Values["controller"] = "Error";
        routeData.Values["action"] = GetActionName(GetStatusCode(ex));

        controller.ViewData.Model = new HandleErrorInfo(ex, " ", " ");
        ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(context), routeData));
    }

    private static void ReturnErrorJson(HttpContext context, Exception ex)
    {
        var json = string.Format(@"success: false, error:""{0}""", ex.Message);
        context.Response.ContentType = "application/json";
        context.Response.Write("{" + json + "}");
    }

    private static int GetStatusCode(Exception ex)
    {
        return ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
    }

    private static bool IsAjaxRequest(HttpRequest request)
    {
        return request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest";
    }

    private static string GetActionName(int statusCode)
    {
        string actionName;

        switch (statusCode)
        {
            case 404:
                actionName = "NotFound";
                break;

            case 400:
                actionName = "InvalidRequest";
                break;

            case 401:
                actionName = "AccessDenied";
                break;

            default:
                actionName = "ServerError";
                break;
        }

        return actionName;
    }

    public static bool IsDebug
    {
        get
        {
            bool debug = false;

#if DEBUG
            debug = true;
#endif
            return debug;
        }
    }
}

错误控制器

public class ErrorController : Controller
{
    public ActionResult AccessDenied()
    {
        return View("AccessDenied");
    }

    public ActionResult InvalidRequest()
    {
        return View("InvalidRequest");
    }

    public ActionResult NotFound()
    {
        return View("NotFound");
    }

    public ActionResult ServerError()
    {
        return View("ServerError");
    }
}

服务器错误视图

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    ServerError
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>ServerError</h2>

    <% if (Model.Exception != null ) { %>
        <p>
          Controller: <%= Model.ControllerName %>
        </p>
        <p>
          Action: <%= Model.ActionName %>
        </p>
        <p>
          Message: <%= Model.Exception.Message%>
        </p>
        <p>
          Stack Trace: <%= Model.Exception.StackTrace%>
        </p>
    <% } %>

</asp:Content>
于 2012-07-18T14:12:56.110 回答