配置httpErrors元素以显示通用错误页面

时间:2014-03-19 13:15:59

标签: c# asp.net .net asp.net-mvc asp.net-mvc-4

如何配置web.config中的httpErrors元素,以根据引发的特定HTTP错误显示常规错误页面?

我正在使用ASP.NET MVC 4.NET 4.5

我在我的网络应用程序的根目录中有以下文件:

403.html
404.html
500.html

我在web.config中有以下设置:

<system.webServer>
     <validation validateIntegratedModeConfiguration="false" />
     <httpErrors errorMode="Custom">
          <remove statusCode="403" />
          <remove statusCode="404" />
          <remove statusCode="500" />
          <error statusCode="403" path="403.html" responseMode="File" />
          <error statusCode="404" path="404.html" responseMode="File" />
          <error statusCode="500" path="500.html" responseMode="File" />
     </httpErrors>
</system.webServer>

我通过这样做来测试上述内容:

throw new System.Web.HttpException(403, "403");

这对我来说非常合适,根据上述HTTP错误之一显示正确的HTML文件。

我想放弃上面的HTML文件,而是显示我的Views/Shared文件夹中的常规错误页面。它被称为Error.cshtml。我不确定如何更改以上内容以显示此新错误页面?

我已将existingResponse设置为AutoReplacePassThrough,但它只显示一个白页。我已将path更改为path="/Error"path="Views/Shared/Error"等几种变体,但这也无效。

2 个答案:

答案 0 :(得分:0)

您需要为此定义控制器。您的行动可以像

一样简单
public ActionResult Error()
{
    return View("~/Views/Shared/Error.cshtml");
}

但是如果你想使用ASP.NET MVC机制进行错误页面显示,你仍然需要它。

使用上面的操作定义控制器后(假设控制器名称也是错误),您可以像编辑任何其他ASP.NET MVC页面一样编写URL:Error/Error

更新。以下是配置示例:

<httpErrors errorMode="Custom"
            defaultResponseMode="ExecuteURL"
            defaultPath="/Error/Error>
</httpErrors>

答案 1 :(得分:0)

您可以捕获Global.asax中的所有错误

 protected void Application_Error(object sender, EventArgs e)
        {
            var httpContext = ((MvcApplication)sender).Context;
            var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
            var currentController = " ";
            var currentAction = " ";
            if (currentRouteData != null)
            {
                if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
                {
                    currentController = currentRouteData.Values["controller"].ToString();
                }

                if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
                {
                    currentAction = currentRouteData.Values["action"].ToString();
                }
            }
            var ex = Server.GetLastError();
            var url = Request.RawUrl;
            var controller = new ErrorController();
            var routeData = new RouteData();
            var action = "Error";
            httpContext.ClearError();
            httpContext.Response.Clear();
            httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500;
            httpContext.Response.TrySkipIisCustomErrors = true;
            routeData.Values["controller"] = "Error";
            routeData.Values["action"] = action;
            controller.ViewData.Model = new NameSpace.HandleErrorInfo(ex, currentController, currentAction);
            ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
        }

在此之前创建一个模型,用于输出错误信息:

public class HandleErrorInfo
    {
        public string ActionName { get; set; }
        public string ControllerName { get; set; }
        public Exception Exception { get; set; }
        public HandleErrorInfo(Exception exception, string controllerName,
            string actionName)
        {
            this.ActionName = actionName;
            this.ControllerName = controllerName;
            this.Exception = exception;
        }
    }

错误视图:与上述错误模型紧密绑定。这会显示所有错误:

@model NameSpace.HandleErrorInfo
@{
    ViewBag.Title = "Error";
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>Error Page</title>
    <link href="@Url.Content("../../Content/site.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("../../Content/css/menu.css")" rel="stylesheet" type="text/css" />
</head>
<body>
           <div class="container">
            <div>
                <table id="tblError" visible="false" cellspacing="2" cellpadding="2" width="90%"
                    border="0" style="margin-left: 50px">
                    <tr>
                        <td align="center" class="pageTitle">
                            Application Error
                        </td>
                    </tr>
                    <tr>
                        <td style="font-family: Arial; font-weight: bold; font-size: 10pt; text-align: center">
                            <br />
                            We are sorry, but an unhandled error occured on the server. The server administrator
                            has been notified and error logged. Please find error details below:
                            <br />
                            <br />
                        </td>
                    </tr>
                    <tr>
                        <td width="40%" align="center">
                            <div id="ErrorInfo">
                                <table>
                                    <tr>
                                        <td class="tdCol1Align">
                                            <b>Controller Name :</b>
                                        </td>
                                        <td class="tdCol2Align">
                                            <b>@Model.ControllerName</b>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="tdCol1Align">
                                            <b>Action Name:</b>
                                        </td>
                                        <td class="tdCol2Align">
                                            <b>@Model.ActionName</b>
                                        </td>
                                    </tr>
                                </table>
                                <br />
                                <br />
                                <b>Error Description:</b><br />
                                <br />
                                <p>
                                    @Model.Exception</p>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <br />
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        <div class="footer">
            <p>
               xyz            </p>
        </div>
    </div>
</body>
</html>

错误视图的控​​制器:

 public class ErrorController : Controller
    {
        /// <summary>
        /// Action Method for Rendering Error View upon Error Occurance
        /// </summary>
        /// <returns></returns>
        public ActionResult Error()
        {
            return View();
        }
    }
相关问题