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