ASP.NET MVC 2中的自定义403错误页面

时间:2014-09-15 13:24:44

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

我想在ASP.NET MVC 2应用程序中显示自定义403页面。我按照link进行了跟踪。我在配置文件中添加了以下内容:

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

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

3 个答案:

答案 0 :(得分:6)

在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>

答案 1 :(得分:1)

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

 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视图。要对此进行测试,请从Login Controller的Index操作中抛出异常,如下所示:

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>

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

尝试这种方法并查看。

答案 2 :(得分:0)

这里有许多好的建议;对我来说,它是在视觉工作室和视觉工作室之间发生的,因为我的web项目被指定加载到它的配置中,因此在同一个端口启动了一个不同的Web项目,所以它只是刷新了我的其他项目的错误(不管我对第二个web项目做了什么改变,都没有global.asax。

根本问题是我的其他网站在visual studio中配置了相同的端口,因此由于解决方案项目订单和耗尽端口而导致其首先加载。我把它改成了另一个端口,问题就消失了。