0

Before reading, bear in mind that HtmlHelperExtensions is a static class as well as the method I am invoking and the code inside the method is wrapped up with a try-catch

I have Views/Shared/_layoutDefault.cshtml file (check the code below). When the code is executed I randomly get a NullReferenceException in @HtmlHelperExtensions.GetNewRelicHtml() line. HtmlHelperExtensions is a static class.

I have changed this code multiple times but the problem's still there.

What I have tried.

  • Wrap the code up with a try-catch, the exception is thrown and the catch doesn't catch it even if the try-catch is catching the base class for all exceptions (System.Exception). BUT if it had worked, It wouldn't have been the best solution because I am just hiding the problem.
  • I have put just one line code like this @(new HtmlString(NewRelicTracker.GetBrowserTimingHeader())). It fails randomly as well
  • I moved everything to a single function in the code-behind. In this case, HtmlHelperExtensions (actual code) and call it like this @HtmlHelperExtensions.GetNewRelicHtml() and still fails. (Please check out the code below)
  • I have checked StackOverflow and have found similar issues but nothing worked for me.

The problem seems only to happen when the view invokes any method that contains this line NewRelicTracker.GetBrowserTimingHeader(); (Please check the code of GetBrowserTimingHeader function below)

Do you have any idea why is this happening?

_layoutDefault.cshtml file

<head>
<!-- to change class="no-js" to "js" before rendering the page to avoid FOUC -->
<script>(function (H) { H.className = H.className.replace(/\bno-js\b/, 'js') })(document.documentElement)</script>

@RenderSection("Styles", required: false)

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

@HtmlHelperExtensions.GetNewRelicHtml()

<link href="@TempData["StyleSheet"].ToString()" rel="stylesheet" type="text/css" />

GetNewRelicHtml is in a static class called HtmlHelperExtensions. Below it's the code.

HtmlHelperExtensions.cs

public static IHtmlString GetNewRelicHtml()
    {
        try
        {
            var newRelicString = NewRelicTracker.GetBrowserTimingHeader();
            return new HtmlString(string.IsNullOrEmpty(newRelicString) 
                                    ? "<!-- New Relic Header (Empty) -->" 
                                    : newRelicString);
        }
        catch (Exception ex)
        {
            return new HtmlString("<!-- New Relic Header (Empty) -->");
        }
    }

NewRelicTracker.cs

public static string GetBrowserTimingHeader()
    {
        try
        {
            return NewRelic.Api.Agent.NewRelic.GetBrowserTimingHeader();
        }
        catch (Exception)
        {
            return string.Empty;
        }
    }

Error

Exception thrown

  • 4
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – CodeNotFound Mar 13 '18 at 17:08
  • If it is that easy, where is the instance that is throwing the null reference exception? Bear in mind that HtmlHelperExtensions is a static class as well as the method I am invoking and the code inside the method is wrapped up with a try-catch. – Daniel Botero Correa Mar 13 '18 at 17:21
  • 4
    So what I've realized with ASP.NET Razor errors, is that the error actually happens at a line above or below t he reported line. Are you confident that `TempData["StyleSheet"]` doesn't return null? – ColinM Mar 13 '18 at 17:25
  • Yes, TempData is initialized right before the return View(...) – Daniel Botero Correa Mar 13 '18 at 17:31
  • 1
    Have you tried stepping through the cshtml code to verify that `TempData` contains a `StyleSheet` key? – ColinM Mar 13 '18 at 17:32
  • The problem only shows up in the server. I can't really debug this easily. But based on the code, that shouldn't be the problem. But I am going to take that into account. That would make more sense that the CodeNotFound's answer. – Daniel Botero Correa Mar 13 '18 at 17:36
  • 3
    To add to @ColinM's question - is `TempData["StyleSheet"]` only called **once** in all of your controllers and views that use this layout? `TempData` values are deleted as soon as they are accessed, so if you try to access it again you will have a `null` value. It might explain "randomness" of this error if you are calling it twice in the same request somewhere. Putting a raw call to `TempData` in a view like this is asking for trouble. `TempData` is not a replacement for `models` or `ViewData`. – NightOwl888 Mar 13 '18 at 18:32

1 Answers1

0

ColinM 21, you were right! Completely right!

So what I've realized with ASP.NET Razor errors, is that the error actually happens at a line above or below t he reported line. Are you confident that TempData["StyleSheet"] doesn't return null?

Even if Razor was telling me the error was in line 13. The actual error was indeed in line 15.

NightOwl888. Thanks for your comment as well. You were right as well.

To add to @ColinM's question - is TempData["StyleSheet"] only called once in all of your controllers and views that use this layout? TempData values are deleted as soon as they are accessed, so if you try to access it again you will have a null value. It might explain "randomness" of this error if you are calling it twice in the same request somewhere. Putting a raw call to TempData in a view like this is asking for trouble. TempData is not a replacement for models or ViewData

Thanks guys. First time I saw this kind of misleading errors.

I just put all my c# code out of the Razor View. That's how I ended up knowing that TempData["StyleSheet"] was causing this NullReferenceException.

========================== Edited 29 March 2018 ==========================

The randomness was due to a missing await next to the Async function I was using to set the styles in TempData.