0

I have an ASP.NET 4.5 MVC application written in C#. I'm using VS 2019. I have successfully deployed this project in the past, but this time, after I publish and move the code to the server, I am getting the following error:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
AI.Controllers.HomeController.Index() +174
lambda_method(Closure , ControllerBase , Object[] ) +86
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +228 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +34
System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +38
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +69 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +41 System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +71 System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +387 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +42 System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +38 System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +188 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +38 System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +68
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +52
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +39 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +38 System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +43 System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +68
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +602
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +195
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +128

Version Information:

  • Microsoft .NET Framework Version:4.0.30319;
  • ASP.NET Version:4.7.3770.0

The application works fine when I run it in debug mode in VS2019; I only get this error after I deploy. I can't set any breakpoints or find out what might be wrong in the deployed code, and the stack trace doesn't tell me where my error is either -- if the "+174" is supposed to be a line number in the source code, that's the last line in the file.

The second line in the stack trace is lambda_method(Closure , ControllerBase , Object[] ) +86 but there are no lambda expressions in the c# of the HomeController.sc file, so that seems to be a red herring as well.

Here is the complete code in my HomeController.cs file:

using System.Reflection;
using System.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AI.auth;
using AI.util;
using AI.Models;

namespace AI.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public class AjaxRequestAttribute : ActionMethodSelectorAttribute
        {
            public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
            {
                return controllerContext.HttpContext.Request.IsAjaxRequest();
            }
        }

        protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new JsonNetResult
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior
            };
        }

        public ActionResult TestBlank() // can be removed after testing
        {
            return View("~/Views/Shared/PageNotFound.cshtml");
        }

        public ActionResult Index()
        {
            //do initial routing and authorization
            bool thereAreClaims = false;

            UserContext uc = new UserContext();

            User thisUser = (User)Session["userInfo"];
            if (thisUser.ACCESS_ID == "") { return RedirectToRoute(new { controller = "Home", action = "NotAuthorized" }); }

            //if (thisUser.ut.IS_STUDENT)
            //{
            thereAreClaims = StudentContext.checkClaims(thisUser.ACCESS_ID);
            //}
            if (thereAreClaims) { thisUser.ut.IS_STUDENT = true; }

            if (thisUser.ut.IS_ADMIN)
            {
                return RedirectToRoute(new { controller = "Admin", action = "Claims" }); // need to get action_security when we get there.
            }
            else
            {
                if (thisUser.ut.IS_STUDENT)
                {
                    if (thisUser.ut.IS_EDUCATOR) // 
                    {

                        if (thereAreClaims)
                        {
                            return RedirectToRoute(new { controller = "Home", action = "GettingStarted" }); // choice page
                        }
                        else
                        {
                            return RedirectToRoute(new { controller = "Educator", action = "GettingStarted" }); // need to get action_security when we get there.
                        }
                    }
                    else
                    {
                        if (thereAreClaims)
                        {
                            return RedirectToRoute(new { controller = "Student", action = "GettingStarted" }); // need to get action_security when we get there.
                        }
                        else
                        {
                            return RedirectToRoute(new { controller = "Home", action = "NoClaimsStudent" });
                        }
                    }
                }
                else
                {
                    if (thisUser.ut.IS_EDUCATOR)
                    {
                        return RedirectToRoute(new { controller = "Educator", action = "GettingStarted" }); // need to get action_security when we get there.
                    }
                    else
                    {
                        return RedirectToRoute(new { controller = "Home", action = "NotAuthorized" });
                    }
                }
            }
        }

        // GET: /Home/NotAuthorized
        public ActionResult NotAuthorized()
        {
            return View("~/Views/Shared/NoAuth.cshtml");
        }

        public ActionResult NotAuthorizedStudent() 
        {
            return View("~/Views/Shared/NoAuthStudent.cshtml");
        }

        public ActionResult NotAuthorizedEducator() 
        {
            return View("~/Views/Shared/NoAuthEducator.cshtml");
        }

        public ActionResult NotAuthorizedToDownload()
        {
            return View("~/Views/Shared/NoAuthViewDoc.cshtml");
        }

        public ActionResult FileNotFound()
        {
            return View("~/Views/Shared/NoFile.cshtml");
        }

        public ActionResult NoClaimsStudent()  // but this one *should* have the photo
        {
            return View("~/Views/Shared/NoClaimsStudent.cshtml");
        }

        //[AuthorizeView]
        public ActionResult GettingStarted() 
        {
            return View("~/Views/Shared/Choice.cshtml");
        }

        public ActionResult PageNotFound()
        {
            return View("~/Views/Shared/PageNotFound.cshtml");
        }

        public ActionResult UnMask()
        {
            string action_data = "Home/UnMask";
            GlobalConfigContext gcc = new GlobalConfigContext();
            GlobalConfig gc = gcc.getGlobalConfig();
            if ((bool)Session["impersonate"] && (string)Session["orig_access_id"] != "" )
            {
                UserContext uc = new UserContext();
                User unMasked = uc.getUserInfo((string)Session["orig_access_id"]);

                if (unMasked.CAN_IMPERSONATE)
                {
                    Session["impersonate"] = false;
                    Session["orig_access_id"] = "";
                    Session["userInfo"] = (User)unMasked;
                    Session["username"] = (string)unMasked.ACCESS_ID;
                }
                else
                {
                    LoggingContext.Log("Unauthorized access to page", action_data, unMasked.ACCESS_ID);
                }
            }
            else
            {
                LoggingContext.Log("Invalid attempt to impersonate", action_data, (string)Session["orig_access_id"]);
            }

            return RedirectToRoute(new { controller = "Home", action = "Index" });
        }

        public void logtest ()
        {
             LoggingContext.Log("Logtest", "Home/Logtest", (string)Session["username"]);
        }
    }
}

Any suggestions for how to debug this problem? Is it possible that it is a problem with .net versioning? The target version in the VS project is 4.5 so I'm not sure where the Version:4.7.3770.0 is coming from.Thanks for any suggestions

BTW: I looked at What is a NullReferenceException, and how do I fix it? but the problem is that I am unable to debug after deployment and in debug mode it works fine

Ned Balzer
  • 35
  • 6
  • What's on line 174? – Fildor May 03 '21 at 15:11
  • 4
    .NET Framework 4.5 has been out of support for 5 years. Have you considered upgrading to .NET Framework 4.8? It's a pretty easy upgrade. Have you tried deploying your app in Debug configuration instead of Release to get more info? One potential source of error is: `User thisUser = (User)Session["userInfo"];` If you access any property of `thisUser` such as `ACCESS_ID` when `thisUser` is null, you'll get the error you got. – mason May 03 '21 at 15:11
  • @Fildor thanks -- I have looked through the suggested question but didn't find anything. Line 174 is the very last (empty) line of the HomeController.cs file -- there's an extra carriage return after the curly brace that closes the namespace block. – Ned Balzer May 03 '21 at 15:32
  • 2
    If nothing else, add some logs to the db or file somewhere and see. It looks like you're taking the existence of data for granted in some cases; add some logs around those. Or...just guard your code against NREs and deal with them. – ChiefTwoPencils May 03 '21 at 15:32
  • @mason, thanks. I tried upgrading to .net 4.7 but it told me that I had a nuget package (DocumentFormat.OpenXML) that was not compatible and I was unable to install a newer version than 2.12.3. Session["userinfo"] is populated in global.asax Sesssion_Start. But I will look at that because the authentication on the server is different than in local machine debug mode. But I didn't change anything about that part of the code, so I am not hopeful. – Ned Balzer May 03 '21 at 15:35
  • 1
    Running into a single error when trying to upgrade to newer .NET Framework isn't really a good excuse not to upgrade. .NET Framework 4.5 has been [out of support for 5 years](https://devblogs.microsoft.com/dotnet/support-ending-for-the-net-framework-4-4-5-and-4-5-1/). **It's not receiving security updates**, it's not getting feature improvements or bug fixes or anything. There's really not a good excuse to still be on 4.5. There is a [stable version of DocumentFormat.OpenXML](https://www.nuget.org/packages/DocumentFormat.OpenXml/2.12.3) that runs on newer .NET Frameworks. – mason May 03 '21 at 15:46
  • I found the problem. It was indeed an issue with Session["userinfo"] being null. There was some badly written code that didn't populate that session variable in this particular server environment. Thanks for your help. @mason we are in the process of rewriting all of our apps in .NET5 (core), but we are a two person shop with more than 20 legacy webapps to maintain so it will take us awhile. But I can do a little more work and at least get this one to 4.8 -- thanks for your help. – Ned Balzer May 03 '21 at 17:35

0 Answers0