ASP.NET MVC应用程序中失败的Windows身份验证的自定义错误页面

时间:2014-02-25 15:45:51

标签: c# asp.net-mvc asp.net-mvc-5 windows-authentication custom-error-pages

根据How to use custom Errors page in Windows Authentication(虽然从未标记为答案),您必须添加IIS HTTP错误处理程序以“捕获”失败的Windows身份验证并提供自定义错误页面。

然而,403永远不会到达,失败的WinAuth以401 Unauthorized结束。但是,如果我为401添加IIS HTTP错误处理程序,NTLM身份验证过程将不再起作用(在内部也使用401)。

当Windows身份验证失败时,任何人都有自定义错误页面的工作解决方案(不是静态的,我想执行MVC控制器操作!)

1 个答案:

答案 0 :(得分:0)

下面的代码并不完全符合您的需要,但这就是我处理未处理的异常的方法。您可以根据状态代码或异常类型对此进行更改以进行不同的路由。 (这来自Global.asax)

 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", "Global");
                int status = 0;

                if (ex.GetType() == typeof(HttpException))
                {
                    var httpException = (HttpException)ex;
                    var code = httpException.GetHttpCode();
                    status = code;
                }
                else
                {
                    status = 500;
                }

                //Create a new error based off the exception and the error status.
                NameSpace.Models.ErrorModel Error = new ErrorModel(status, ex);
                string innerException = "";
                if (ex.InnerException != null)
                {
                    innerException = "\n Inner Ex: " + ex.InnerException.StackTrace;
                }

                log.Error("Error Id: " + Error.ErrorId + " Error: " + ex.Message + ". Stack Trace: " + ex.StackTrace + innerException);
                routeData.Values.Add("error", Error);

                IController errorController = new NameSpace.Controllers.ErrorController();
                errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));


            }

更新:道歉,我没有完全阅读你的帖子。如果您要在应用程序中执行LDAP身份验证,则可以利用上述代码来捕获并使用控制器处理错误。很遗憾,我无法就上述问题提供直接指导。