MVC4 httpException.GetHttpCode();导致NullReferenceException

时间:2013-10-22 10:30:43

标签: c# asp.net-mvc entity-framework localhost global-asax

我不得不重构整个应用程序,从VS Express DB到使用Visual Studio 2012。 我不得不删除所有模态并重新添加它们。

现在,当我尝试运行应用程序时,它一直落在Global.Asax.cs

它不断抛出NullReferenceException - > int exceptionType = httpException.GetHttpCode();

我的应用程序甚至没有运行,似乎本地主机服务器甚至没有加载我的网站

请帮助

protected void Application_Error()
        {

            if (Context.IsCustomErrorEnabled)
                ShowCustomErrorPage(Server.GetLastError());

        }
        private void ShowCustomErrorPage(Exception exception)
        {
            var httpException = exception as HttpException;
            if (exception != null)
            {
                exception = httpException;
            }

            else
            {

                exception = new HttpException(500, "Internal Server Error", exception);
            }
            Response.Clear();
            Server.ClearError();
            var routeData = new RouteData();
            routeData.Values.Add("Controller", "Error");
            routeData.Values.Add("fromAppErrorEvent", true);

            int exceptionType = httpException.GetHttpCode();

            switch (exceptionType)
            {


                case 403:
                    routeData.Values.Add("action", "HttpError403");
                    break;

                case 404:
                    routeData.Values.Add("action", "NotFound");
                    break;

                case 500:
                    routeData.Values.Add("action", "HttpError500");
                    break;

                default:
                    routeData.Values.Add("action", "GeneralError");
                    routeData.Values.Add("httpStatusCode", httpException.GetHttpCode());
                    break;
            }



            IController controller = new Login.Controllers.ErrorController();
            controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

1 个答案:

答案 0 :(得分:2)

在上面的逻辑中,httpException可以是null - 尝试将代码更改为以下内容:

HttpException httpException = exception as HttpException
    ?? new HttpException(500, "Internal Server Error", exception);

Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values.Add("Controller", "Error");
routeData.Values.Add("fromAppErrorEvent", true);

int exceptionType = httpException.GetHttpCode();