【问题标题】:Custom 403 error page in ASP.NET MVC 2ASP.NET MVC 2 中的自定义 403 错误页面
【发布时间】:2014-09-15 13:24:43
【问题描述】:

我想在我的 ASP.NET MVC 2 应用程序中显示一个自定义 403 页面。我关注了link。我在配置文件中添加了以下内容:

<httpErrors>
      <remove statusCode="403" subStatusCode="-1"/>
      <error statusCode="403" path="/403.htm" responseMode="ExecuteURL"/>
</httpErrors>

我仍然看到默认的 ASP.NET 403 错误页面。怎么了?

【问题讨论】:

  • @HirenKagrana 试过了。对我不起作用。获得 500 并且应用程序无法启动。此外,我没有任何特定要求,例如重定向。我只想要一个自定义错误页面。

标签: c# asp.net asp.net-mvc asp.net-mvc-3 custom-error-pages


【解决方案1】:

在 web.config 中添加以下标记:

 <customErrors mode="On" defaultRedirect="/error/error">
  <error statusCode="400" redirect="/error/badrequest" />
  <error statusCode="403" redirect="/error/forbidden" />
  <error statusCode="404" redirect="/error/notfound" />
  <error statusCode="414" redirect="/error/urltoolong" />
  <error statusCode="503" redirect="/error/serviceunavailable" />
</customErrors>

使用以下代码添加一个名为 ErrorInfo 的视图模型:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Gunaatita.ViewModel
{
    public class ErrorInfo
    {
        public string Message { get; set; }
        public string Description { get; set; }
    }
}

使用以下代码创建控制器名称 ErrorController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Gunaatita.ViewModel;

namespace Gunaatita.Controllers
{
    [HandleError]
    public class ErrorController : Controller
    {
        public ActionResult Error()
        {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.Message = "An Error Has Occured";
            errorInfo.Description = "An unexpected error occured on our website. The website administrator has been notified.";
            return PartialView(errorInfo);
        }
        public ActionResult BadRequest()
        {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.Message = "Bad Request";
            errorInfo.Description = "The request cannot be fulfilled due to bad syntax.";
            return PartialView("Error", errorInfo);
        }
        public ActionResult NotFound()
        {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.Message = "We are sorry, the page you requested cannot be found.";
            errorInfo.Description = "The URL may be misspelled or the page you're looking for is no longer available.";
            return PartialView("Error", errorInfo);
        }

        public ActionResult Forbidden()
        {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.Message = "403 Forbidden";
            errorInfo.Description = "Forbidden: You don't have permission to access [directory] on this server.";
            return PartialView("Error", errorInfo);
        }
        public ActionResult URLTooLong()
        {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.Message = "URL Too Long";
            errorInfo.Description = "The requested URL is too large to process. That’s all we know.";
            return PartialView("Error", errorInfo);
        }
        public ActionResult ServiceUnavailable()
        {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.Message = "Service Unavailable";
            errorInfo.Description = "Our apologies for the temporary inconvenience. This is due to overloading or maintenance of the server.";
            return PartialView("Error", errorInfo);
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }
}

并使用以下标记更新 \Views\Shared\Error.cshtml:

@model Gunaatita.ViewModel.ErrorInfo
@{
    ViewBag.Title = "Problem";
    Layout = "~/Views/Shared/_LayoutSite.cshtml";
}

<div class="middle-container">


    <link rel="stylesheet" href="/Content/css/thankyou.css">
    <!--- middle Container ---->

    <div class="middle-container">
        <div class="paddings thankyou-section" data-moduleid="2050" id="ContactUsPane">
            @if (Model != null)
            {
                <h1>@Model.Message</h1>
                <p>@Model.Description</p>
            }
            else
            {
                <h1>An Error Has Occured</h1>
                <p>An unexpected error occured on our website. The website administrator has been notified.</p>
            }

            <p><a href="/" class="btn-read-more">Go To Home Page</a></p>
        </div>
    </div>
    <!--- middle Container ---->

</div>

【讨论】:

  • 我正在尝试这个,但ErrorInfo 不是有效类型?我错过了一些参考吗?
  • 我刚刚用 ErrorInfo 类更新了答案。请检查。
【解决方案2】:

默认情况下,MVC 模板实现 HandleErrorAttribute att。我们可以在 Global.asax 中找到它(或者对于 MVC4 在 App_Start\FilterConfig.cs 中)

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)   {
    filters.Add(new HandleErrorAttribute());  
   }

如果在 web.config 中打开 CustomErrors,HandleErrorAttribute 会将用户重定向到默认错误页面。

要通过 HandleErrorAttribute 过滤器启用自定义错误处理,我们需要在应用程序的 Web.config 的 system.web 部分添加 customErrors 元素,如下所示:

<system.web>
  <customErrors mode="On" defaultRedirect="Error.cshtml" />
</system.web>

语法:

<customErrors defaultRedirect="url"   mode="On | Off | RemoteOnly"> 
</customErrors>

我们也可以有单独的视图,根据错误状态代码将用户重定向到特定的视图,如下所示:

<customErrors mode="On">
    <error code="404" path="~/Views/Shared/NotFound.cshtml" /> 
    <error code="500" path="~/Views/Shared/InternalServerError.cshtml" /> 
</customErrors> 

现在让我们看看 HandleErrorAttribute 如何将用户重定向到默认的 Error.cshtml 视图。为了测试这一点,让我们从登录控制器的索引操作中抛出一个异常,如下所示:

public ActionResult Index()  {  
    throw new ApplicationException("Error");  
    //return View();  
}

我们将在默认 MVC 项目的 Shared 文件夹中看到 Errors.cshtml 的默认输出,这将返回正确的 500 状态消息,但我们的堆栈跟踪在哪里??

现在要捕获 Stack Trace,我们需要在 Error.cshtml 中进行一些修改,如下所示:

 @model System.Web.Mvc.HandleErrorInfo
    <hgroup>
      <div class="container">
                <h1 class="row btn-danger">Error.</h1>
    @{
                    if (Request.IsLocal)
                    {
                        if (@Model != null && @Model.Exception != null)
                        {
                            <div class="well row">

                                <h4> Controller: @Model.ControllerName</h4>
                                <h4> Action: @Model.ActionName</h4>
                                <h4> Exception: @Model.Exception.Message</h4>
                                <h5>
                                    Stack Trace: @Model.Exception.StackTrace
                                </h5>
                            </div>

                        }
                        else
                        {
                            <h4>Exception is Null</h4>
                        }
                    }
                    else
                    {
                        <div class="well row">
                            <h4>An unexpected error occurred on our website. The website administrator has been notified.</h4>
                            <br />
                            <h5>For any further help please visit <a href="http://abcd.com/"> here</a>. You can also email us anytime at support@abcd.com or call us at (xxx) xxx-xxxx.</h5>
                        </div>
                    }

                }
    </div>
    </hgroup>

此更改可确保我们看到详细的堆栈跟踪。

试试这个方法看看。

【讨论】:

    【解决方案3】:

    这里有很多好的建议;对我来说,它发生在 Visual Studio 和 Visual Studio 启动了一个不同的 Web 项目到同一个端口,因为我的 Web 项目被指定加载到它的配置中,所以它只是刷新我的另一个项目上的错误(它没有一个 global.asax)无论我对第二个 Web 项目做了什么改变。

    原来的根本问题是我的另一个站点在 Visual Studio 中配置了相同的端口,因此由于解决方案项目顺序并用完端口,它一直先加载。我将其更改为另一个端口,问题就消失了。

    【讨论】:

      猜你喜欢
      • 2018-12-03
      • 2014-06-27
      • 1970-01-01
      • 2015-11-14
      • 2011-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      相关资源
      最近更新 更多