question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

System.NullReferenceException: 'Object reference not set to an instance of an object.' Microsoft.AspNetCore.Http.IHttpContextAccessor.HttpContext.get

See original GitHub issue

I’m running into this error on startup with a fresh clone of the repo today:

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

Microsoft.AspNetCore.Http.IHttpContextAccessor.HttpContext.get 

It is coming from here: https://github.com/enkodellc/blazorboilerplate/blob/141cfdc51c6fb4613899483cbe2ff6a8fa38f311/src/Server/BlazorBoilerplate.Server/Startup.cs#L553

httpContextAccessor HttpContext

I have blazorboilerplate running on another computer without issue. I’m not sure why there’s an error on this one. I’m able to get around the error by patching it with:

diff --git a/src/Server/BlazorBoilerplate.Server/Startup.cs b/src/Server/BlazorBoilerplate.Server/Startup.cs
index 186bd58..cf501a0 100644
--- a/src/Server/BlazorBoilerplate.Server/Startup.cs
+++ b/src/Server/BlazorBoilerplate.Server/Startup.cs
@@ -550,7 +550,7 @@ namespace BlazorBoilerplate.Server
                 // creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
                 var navigationManager = s.GetRequiredService<NavigationManager>();
                 var httpContextAccessor = s.GetRequiredService<IHttpContextAccessor>();
-                var cookies = httpContextAccessor.HttpContext.Request.Cookies;
+                var cookies = httpContextAccessor.HttpContext == null ? null : httpContextAccessor.HttpContext.Request.Cookies;
                 var httpClientHandler = new HttpClientHandler(){ UseCookies = false };
                 if (_environment.IsDevelopment())
                 {
@@ -558,7 +558,7 @@ namespace BlazorBoilerplate.Server
                     httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return true; };
                 }
                 var client = new HttpClient(httpClientHandler);
-                if (cookies.Any())
+                if (cookies != null && cookies.Any())
                 {
                     var cks = new List<string>();

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:7 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
oneparametercommented, May 26, 2021

Although this has been a highly debated subject, the consensus is to not rely on the HTTP context anywhere in a Blazor application. What 12step describes in his comment is something in the line of this:

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@{
    var cookies = new SomeInitialApplicationStateObject
    {
        SomeCookie = await HttpContextAccessor.HttpContext.Request.Cookies
    };
}
<!DOCTYPE html>
<html lang="en">
<head>
  ....
</head>
<body>
    <app>
        <component type="typeof(App)" render-mode="Server" param-InitialApplicationState="@cookies" />
    </app>
</body>
</html>

That’d expose the cookie to the main component. The only hard part is handling cookie expiration. Since the parameters are only really set during the initial request of the page, you will run into expired cookies at some point in time, if the user keeps their browser open for as long as it takes.

So you might opt to put the whole HTTPContext into the model. Which would be a mistake too, because that would keep the one instance of the http context in memory forever. When you do that, it means no more updates can be done to the HttpContext, no updating of cookies that is. Since the HTTP context cookies cannot be edited when the response has started.

What you really want to do is go with another source of state, don’t use cookies, it will only give you problems.

0reactions
enkodellccommented, Aug 13, 2021

I got this issue on my win7 laptop. Used @EmergentCybernetics adjusted code and it seems work for me until I get back to my win10 box. I am closing issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Getting NullReferenceException and object reference not ...
Try without GetString in the if condition if (_httpContextAccessor.HttpContext.Session["CompanyCode"] != null) { queryArgs.
Read more >
HttpContext NULL issue?? System. ...
However, I get System.NullReferenceException: Object reference not set to an instance of an object. at Services.UserRepository.
Read more >
Error when checking if HttpContextAccessor.HttpContext. ...
Hi there. I'm using VS 2019 community, in my application that using .net core MVC I'm trying to check if user signed in...
Read more >
Blazor Server IHttpContextAccessor returning null when ...
Error: System.NullReferenceException: Object reference not set to an instance of an object. at SwordfishCRM.Services.ApplicationDbContext.
Read more >
Access HttpContext in ASP.NET Core
An HttpContext instance is initialized when an HTTP request is received. The HttpContext instance is accessible by middleware and app frameworks ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found