asp.net-mvc-3 – 如何在Asp.Net Mvc 3中显示自定义错误页面?

我想将所有401错误重定向自定义错误页面。我最初在我的web.config中设置了以下条目。
<customErrors defaultRedirect="ErrorPage.aspx" mode="On">
  <error statusCode="401" redirect="~/Views/Shared/AccessDenied.aspx" />
</customErrors>

当使用IIS Express时,我收到库存IIS Express 401错误页面

在不使用IIS Express的情况下,返回空白页。使用Google Chrome的“网络”选项卡检查响应,我看到当页面为空时,标题中返回了401状态

到目前为止我所尝试的是使用this SO answer的建议,因为我使用IIS Express,但无济于事。我已经尝试使用<自定义错误>和< httpErrors>没有运气 – 标准错误或空白页仍然显示

现在的httpErrors部分看起来像above SO questionthe link(我也发现另外一个非常promising answer,但是没有运气 – 空白的回应)

<system.webServer>
  <httpErrors  errorMode="DetailedLocalOnly" existingResponse="Passthrough" >
    <remove statusCode="401"  />
    <error statusCode="401" path="/Views/Shared/AccessDenied.htm" />
  </httpErrors>

 <!-- 
 <httpErrors  errorMode="Custom" 
             existingResponse="Passthrough" 
             defaultResponseMode="ExecuteURL">
      <remove statusCode="401"  />
  <error statusCode="401" path="~/Views/Shared/AccessDenied.htm" 
         responseMode="File" />
 </httpErrors>
 -->
</system.webServer>

我甚至修改了applicationhost.config文件修改了< httpErrors lockAttributes =“allowAbsolutePathsWhenDelegated,defaultPath”>到< httpErrors lockAttributes =“allowAbsolutePathsWhenDelegated”>基于iis.net的信息。在我的努力过程中,我还设法在another SO question中描述了这个错误

如何在Asp.Net Mvc 3中显示自定义错误页面

附加信息

以下控制器操作已使用特定用户的Authorize属性进行装饰。

[HttpGet]
[Authorize(Users = "domain\\userXYZ")]
public ActionResult Edit() 
{
   return GetSettings();
}

[HttpPost]
[Authorize(Users = "domain\\userXYZ")]
public ActionResult Edit(ConfigurationModel model,IList<Shift> shifts)
{
    var temp = model;
    model.ConfiguredShifts = shifts;
    EsgConsole config = new EsgConsole();

    config.UpdateConfiguration(model.ToDictionary());
    return RedirectToAction("Index");
}

解决方法

我使用这些步骤:
// in Global.asax.cs:
        protected void Application_Error(object sender,EventArgs e) {

            var ex = Server.GetLastError().GetBaseException();

            Server.ClearError();
            var routeData = new RouteData();
            routeData.Values.Add("controller","Error");
            routeData.Values.Add("action","Index");

            if (ex.GetType() == typeof(HttpException)) {
                var httpException = (HttpException)ex;
                var code = httpException.GetHttpCode();
                routeData.Values.Add("status",code);
            } else {
                routeData.Values.Add("status",500);
            }

            routeData.Values.Add("error",ex);

            IController errorController = new Kavand.Web.Controllers.ErrorController();
            errorController.Execute(new RequestContext(new HttpContextwrapper(Context),routeData));
        }

        protected void Application_EndRequest(object sender,EventArgs e) {
            if (Context.Response.StatusCode == 401) { // this is important,because the 401 is not an error by default!!!
                throw new HttpException(401,"You are not authorised");
            }
        }

和:

// in Error Controller:
    public class ErrorController : Controller {

        public ActionResult  Index(int status,Exception error) {
            Response.StatusCode = status;
            return View(status);
        }

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

AND错误文件夹中的索引视图:

@* in ~/Views/Error/Index.cshtml: *@

@model Int32    
@{
    Layout = null;
}    
<!DOCTYPE html>    
<html>
<head>
    <title>Kavand | Error</title>
</head>
<body>
    <div>
        There was an error with your request. The error is:<br />
        <p style=" color: Red;">
        @switch (Model) {
            case 401: {
                    <span>Your message goes here...</span>
                }
                break;
            case 403: {
                    <span>Your message goes here...</span>
                }
                break;
            case 404: {
                    <span>Your message goes here...</span>
                }
                break;
            case 500: {
                    <span>Your message goes here...</span>
                }
                break;
            //and more cases for more error-codes...
            default: {
                    <span>UnkNown error!!!</span>
                }
                break;
        }
        </p>
    </div>
</body>
</html>

AND – 最后一步:

<!-- in web.config: -->

<customErrors mode="Off"/>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“WPF...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这...
Some samples are below for ASP.Net web form controls:(from http://www.visualize.uk.com/resources/asp
问题描述: 对于未定义为 System.String 的列,唯一有效的值是(引发异常)。 For columns not defined as System.String, the only vali
最近用到了CalendarExtender,结果不知道为什么发生了错位,如图在Google和百度上找了很久,中文的文章里面似乎只提到了如何本地化(就是显示中文的月份)以及怎么解决被下拉框挡住的问题,谈
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence changed a lot since 1.1. Here is the order: App
静态声明: &#39; Style=&quot;position: relative&quot; AppendDataBoundItems=&quot;True&quot;&gt; (无 或 空 或
以下内容是从网络上搜集资料,然后整理而来的。不当之处,请不吝指教。(The following were from network, and edited by myself. Thanks in a
Imports System Imports System.Reflection Namespace DotNetNuke &#39;*********************************
Ok so you have all seen them: “8 million tools for web development”, “5 gagillion tools that if you
以下内容来源于: http://blog.csdn.net/cuike519/archive/2005/09/27/490316.aspx 问:为什么Session在有些机器上偶尔会丢失? 答:可能和
以下文章提到可以用“http://localhost/MyWebApp/WebAdmin.axd”管理站点: ---------------------------------------------
Visual Studio 2005 IDE相关的11个提高开发效率的技巧 英文原创来源于: http://www.chinhdo.com/chinh/blog/20070920/top-11-vis
C#日期格式化 from: http://51xingfu.blog.51cto.com/219185/46222 日期转化一 为了达到不同的显示效果有时,我们需要对时间进行转化,默认格式为:2007
from: http://www.nikhilk.net/UpdateControls.aspx Two controls that go along with the UpdatePanel and
Open the report in the Designer. In the ToolBox, select/expand the &quot;Report Items&quot; section.
from: http://drupal.org/node/75844 Do this: find which TinyMCE theme you are using. For the sake of
asp.net中给用户控件添加自定义事件 用户控件中定义好代理和事件: public delegate void ItemSavedDelegate(object sender, EventArgs
在Windows版本的Safari中浏览以下的页面。 http://www.asp.net/AJAX/Control-Toolkit/Live/Calendar/Calendar.aspx Calen
http://aspnet.4guysfromrolla.com/articles/021506-1.aspx By Scott Mitchell Introduction When creating