且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何显示Asp.Net MVC 3自定义错误页?

更新时间:2023-02-25 22:51:20

我使用以下步骤:

  //在Global.asax.cs中:
        保护无效的Application_Error(对象发件人,EventArgs的发送){            VAR前= Server.GetLastError()GetBaseException()。            Server.ClearError();
            VAR的RouteData =新的RouteData();
            routeData.Values​​.Add(控制器,错误);
            routeData.Values​​.Add(行动,指数);            如果(ex.GetType()== typeof运算(HttpException)){
                VAR httpException =(HttpException)前;
                变量code = httpException.GetHttp code();
                routeData.Values​​.Add(身份,code);
            }其他{
                routeData.Values​​.Add(身份,500);
            }            routeData.Values​​.Add(错误,前);            一个IController errorController =新Kavand.Web.Controllers.ErrorController();
            errorController.Execute(新的RequestContext(新HttpContextWrapper(上下文)的RouteData));
        }        保护无效Application_EndRequest(对象发件人,EventArgs的发送){
            如果(Context.Response.Status code == 401){//这是很重要的,因为401不是一个错误默认!
                抛出新的HttpException(401,您没有权限);
            }
        }

  //在错误控制器:
    公共类ErrorController:控制器{        公众的ActionResult指数(INT状态,异常错误){
            Response.Status code =状态;
            返回查看(状态);
        }        保护覆盖无效的Dispose(BOOL处置){
            base.Dispose(处置);
        }
    }

和在错误的文件夹的索引视图:

  @ *在〜/查看/错误/ Index.cshtml:* @@model的Int32
@ {
    布局= NULL;
}
<!DOCTYPE HTML>
< HTML和GT;
< HEAD>
    <标题> Kavand |错误< /标题>
< /头>
<身体GT;
    < D​​IV>
        有您的要求的错误。错误是:< BR />
        < p =风格颜色:红色;>
        @switch(型号){
            案例401:{
                    <跨度>您的留言放在这里...< / SPAN>
                }
                打破;
            案例403:{
                    <跨度>您的留言放在这里...< / SPAN>
                }
                打破;
            案例404:{
                    <跨度>您的留言放在这里...< / SPAN>
                }
                打破;
            案例500:{
                    <跨度>您的留言放在这里...< / SPAN>
                }
                打破;
            //多的情况下,更多的错误 - $ C $ ... CS
            默认:{
                    <跨度>未知错误!< / SPAN>
                }
                打破;
        }
        &所述; / P>
    < / DIV>
< /身体GT;
< / HTML>

和-the最后一步:

 <  - 在web.config中:! - ><的customErrors模式=关/>

I want all 401 errors to be be redirected to a custom error page. I have initially setup the following entry in my web.config.

<customErrors defaultRedirect="ErrorPage.aspx" mode="On">
  <error statusCode="401" redirect="~/Views/Shared/AccessDenied.aspx" />
</customErrors>

When using IIS Express I receive the stock IIS Express 401 error page.

In the event when I do not use IIS Express a blank page is returned. Using Google Chrome's Network tab to inspect the response, I see that while the page is blank a 401 status is returned in the headers

What I have tried thus far is using suggestions from this SO answer since I am using IIS Express but to no avail. I have tried using a combination <custom errors> and <httpErrors> with no luck - the standard error or blank page is still displayed.

The httpErrors section looks like this at the moment based on the link from the above SO question ( I also found another very promising answer however no luck - blank response)

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

I have even modified the applicationhost.config file and modified <httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath"> to <httpErrors lockAttributes="allowAbsolutePathsWhenDelegated"> based on information from iis.net. During the course of my endeavours I also managed to stumbled upon this error as described in another SO question.

How do I display custom error pages in Asp.Net Mvc 3?

Additional info

The following controller actions have been decorated with the Authorise attribute for a specific user.

[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");
}

I use these steps:

// 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");
            }
        }

AND:

// 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 the index view in Error folder:

@* 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 -the final step:

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

<customErrors mode="Off"/>