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

Ahm*_*mad 23 error-handling http-error custom-error-pages iis-express asp.net-mvc-3

我希望将所有401错误重定向到自定义错误页面.我最初在web.config中设置了以下条目.

<customErrors defaultRedirect="ErrorPage.aspx" mode="On">
  <error statusCode="401" redirect="~/Views/Shared/AccessDenied.aspx" />
</customErrors>
Run Code Online (Sandbox Code Playgroud)

使用IIS Express时,我收到了IIS Express 401错误页面.

如果我不使用IIS Express,则返回空白页面.使用Google Chrome的"网络"标签检查响应,我看到当页面为空白时,标题中会返回401状态

到目前为止我尝试使用的是这个SO答案中的建议,因为我使用的是IIS Express,但无济于事.我尝试过使用组合<custom errors><httpErrors>没有运气 - 标准错误或空白页仍然显示.

httpErrors部分看起来像这样的基础上,瞬间链接上面的SO问题(我还发现了另一种非常有前途的答案却没有运气-空白响应)

<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>
Run Code Online (Sandbox Code Playgroud)

我甚至已经修改了applicationhost.config文件,并修改<httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath">,以<httpErrors lockAttributes="allowAbsolutePathsWhenDelegated">基于从信息iis.net.在我努力的过程中,我也设法偶然发现了另一个SO问题中描述的这个错误.

如何在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");
}
Run Code Online (Sandbox Code Playgroud)

jav*_*iry 34

我使用这些步骤:

// 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");
            }
        }
Run Code Online (Sandbox Code Playgroud)

和:

// 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

@* 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>
Run Code Online (Sandbox Code Playgroud)

和 - 最后一步:

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

<customErrors mode="Off"/>
Run Code Online (Sandbox Code Playgroud)


Tri*_*dus 11

我无法在web.config和MVC中获得CustomErrors以便一起玩,所以我放弃了.我这样做了.

在global.asax中:

protected void Application_Error()
    {
        var exception = Server.GetLastError();
        var httpException = exception as HttpException;
        Response.Clear();
        Server.ClearError();
        var routeData = new RouteData();
        routeData.Values["controller"] = "Errors";
        routeData.Values["action"] = "General";
        routeData.Values["exception"] = exception;
        Response.StatusCode = 500;
        if (httpException != null)
        {
            Response.StatusCode = httpException.GetHttpCode();
            switch (Response.StatusCode)
            {
                case 403:
                    routeData.Values["action"] = "Http403";
                    break;
                case 404:
                    routeData.Values["action"] = "Http404";
                    break;
            }
        }
        // Avoid IIS7 getting in the middle
        Response.TrySkipIisCustomErrors = true;
        IController errorsController = new GNB.LG.StrategicPlanning.Website.Controllers.ErrorsController();
        HttpContextWrapper wrapper = new HttpContextWrapper(Context);
        var rc = new RequestContext(wrapper, routeData);
        errorsController.Execute(rc);
    }
Run Code Online (Sandbox Code Playgroud)

在ErrorsController中:

public class ErrorsController
{
    public ActionResult General(Exception exception)
    {
        // log the error here
        return View(exception);
    }

    public ActionResult Http404()
    {
        return View("404");
    }

    public ActionResult Http403()
    {
        return View("403");
    }
}
Run Code Online (Sandbox Code Playgroud)

在web.config中:

<customErrors mode="Off" />
Run Code Online (Sandbox Code Playgroud)

无论在何处或如何创建错误,这对我都有用.401现在不在那里处理,但你可以很容易地添加它.


The*_*ing 9

也许我错过了一些东西,但MVC有一个ErrorHandlerAttribute使用自定义错误的默认全局.这个解释相当不错这里.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}
Run Code Online (Sandbox Code Playgroud)

您需要做的就是custom errors在配置中打开,然后设置自定义错误重定向,最好是静态HTML文件(如果应用程序出错).

<customErrors mode="On" defaultRedirect="errors.htm">
    <error statusCode="404" redirect="errors404.htm"/>
</customErrors>
Run Code Online (Sandbox Code Playgroud)

如果您愿意,也可以指向自定义Controller以显示错误.在下面的示例中,我刚使用默认路由到Controller命名Error,并调用了一个操作Index,并且命名了字符串参数id(以接收错误代码).你当然可以使用你想要的任何路由.您的示例无效,因为您尝试直接链接到Views目录而不通过Controller.MVC .NET不Views直接向文件夹提供请求.

<customErrors mode="On" defaultRedirect="/error/index/500">
    <error statusCode="404" redirect="/error/index/404"/>
</customErrors>
Run Code Online (Sandbox Code Playgroud)

ErrorHandlerAttribute还可以广泛地使用Controllers/Actions重定向错误名为Views有关Controller.例如,要显示出现类型异常时的View命名MyArgumentError,ArgumentException您可以使用:

[ControllerAction,ExceptionHandler("MyArgumentError",typeof(ArgumentException))]
public void Index()
{
   // some code that could throw ArgumentExcepton
}
Run Code Online (Sandbox Code Playgroud)

当然另一种选择是更新库存Error页面Shared.

  • 问题是IIS express已经处理了其他状态代码(而不是500),因此您建议的并不总是有效(取决于IIS设置).IIS只显示自己的页面,我们永远不会在asp中查看它. (2认同)

归档时间:

查看次数:

29687 次

最近记录:

6 年,5 月 前