简体   繁体   English

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

[英]Custom 403 error page in ASP.NET MVC 2

I want to show a custom 403 page in my ASP.NET MVC 2 application. 我想在我的ASP.NET MVC 2应用程序中显示自定义403页面。 I followed following link . 我按照以下链接 I added following to my config file: 我在配置文件中添加了以下内容:

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

I am still seeing the default ASP.NET 403 error page. 我仍然看到默认的ASP.NET 403错误页面。 What's wrong? 怎么了? 默认的ASP.NET 403错误页面

Add below markup in web.config: 在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>

Add a view model named ErrorInfo with below code: 使用以下代码添加名为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; }
    }
}

Create a controller name ErrorController with below code: 使用以下代码创建一个控制器名称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);
        }
    }
}

And update \\Views\\Shared\\Error.cshtml with below markup: 并使用以下标记更新\\ 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>

By default MVC template implements HandleErrorAttribute att. 默认情况下,MVC模板实现HandleErrorAttribute att。 We can find this in the Global.asax (or for MVC4 in the App_Start\\FilterConfig.cs) 我们可以在Global.asax中找到它(或者在App_Start \\ FilterConfig.cs中找到MVC4)

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

HandleErrorAttribute redirects user to the default Error page if CustomErrors is turned ON in web.config. 如果在web.config中打开CustomErrors,HandleErrorAttribute会将用户重定向到默认的错误页面。

To enable custom error handling by HandleErrorAttribute filter, we need to add customErrors element in system.web section of the application's Web.config as shown below: 要通过HandleErrorAttribute过滤器启用自定义错误处理,我们需要在应用程序的Web.config的system.web部分中添加customErrors元素,如下所示:

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

Syntax : 句法 :

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

We can have separate views also to redirect User to the specific view based on the error status codes, as shown below: 我们也可以有单独的视图,根据错误状态代码将用户重定向到特定视图,如下所示:

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

Now lets see how HandleErrorAttribute redirects user to default Error.cshtml view. 现在让我们看看HandleErrorAttribute如何将用户重定向到默认的Error.cshtml视图。 To test this, lets throw an exception from Index action of Login Controller as shown below: 要对此进行测试,请从Login Controller的Index操作中抛出异常,如下所示:

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

We will see the default output from Errors.cshtml in the Shared folder of a default MVC project which will return a correct 500 status message but where is our Stack Trace?? 我们将在默认MVC项目的Shared文件夹中看到Errors.cshtml的默认输出,它将返回正确的500状态消息但是我们的堆栈跟踪在哪里?

Now to capture Stack Trace we need to do couple of modifications in Error.cshtml, as shown below: 现在要捕获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>

This change ensure that we see detailed stack trace. 此更改可确保我们看到详细的堆栈跟踪。

Try this approach and see. 尝试这种方法,看看。

Many good suggestions here; 这里有很多好的建议; for me, it was occurring under visual studio and visual studio started a different web project into the same port as my web project was specified to load in it's config, so it was just refreshing the error on my other projet (which doesn't have a global.asax) no matter what change I made to the second web project. 对我来说,它发生在视觉工作室和视觉工作室开始一个不同的web项目进入同一个端口,因为我的web项目被指定加载它的配置,所以它只是刷新我的其他项目的错误(没有一个global.asax)无论我对第二个Web项目做了什么改变。

The underlying issue turned out to be that my other site had the same port configured in visual studio so it kept loading first due to the solution project order and using up the port. 根本问题是我的其他网站在visual studio中配置了相同的端口,因此由于解决方案项目订单和耗尽端口而导致其首先加载。 I changed it to another port and the issue went away. 我把它改成了另一个端口,问题就消失了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM