Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4840

Blazor Hot Reload problem with HttpContextAccessor

$
0
0

when i launch my application it works fine but when i change something and save it (doesn't matter in which component) hot reload is not working as expected it says:

System.NullReferenceException: 'Object reference not set to an instance of an object.'Microsoft.AspNetCore.Http.IHttpContextAccessor.HttpContext.get returned null.System.NullReferenceException  HResult=0x80004003  Message=Object reference not set to an instance of an object.  Source=WEBv3  StackTrace:   at WEBv3.Components.Layout.NavMenu.BuildRenderTree(RenderTreeBuilder __builder) in E:\projects\e-Schedule\WEBv3\Components\Layout\NavMenu.razor:line 84

As i can see the problem is with the HttpContextAccessor. As i know it works or request response and maybe that is why it not working correct with the Hot Reload. Maybe i should do some kind storage and store it in variable or is there a way to change the wat HotReload works?

here is my NavMenu component:

@inject IHttpContextAccessor accessor@inject ILocalStorageService LocalStorage@inject IJSRuntime JS@inject NavigationManager UriHelper@using System.Net.Http;@using System.Diagnostics;@using System.Net;@using Blazored.LocalStorage@rendermode InteractiveServer<nav class="navbar navbar-expand-lg fixed-top shadow-sm"><div class="container-fluid"><a class="navbar-brand" asp-controller="Home" asp-action="Index"><img src="img/favicon.png" alt="Logo" height="32" class="d-inline-block align-text-top">                e-Schedule</a><button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"><i class="fa-solid fa-bars"></i></button><div class="collapse navbar-collapse" id="navbarNav"><ul class="navbar-nav me-auto"><li class="nav-item"><NavLink class="nav-link" href="/"><span class="bi bi-list-nested-nav-menu" aria-hidden="true">Начало</span></NavLink></li><li class="nav-item"><NavLink class="nav-link" href="SubGroup"><span class="bi bi-list-nested-nav-menu" aria-hidden="true">Подгрупи</span></NavLink></li><li class="nav-item"><a class="nav-link" asp-controller="Prepaire" asp-action="Flows">Потоци</a></li><li class="nav-item dropdown"><a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown" aria-expanded="false">Меню</a><ul class="dropdown-menu"><li><a class="dropdown-item" asp-controller="Home" asp-action="Index">Подменю 1</a></li><li><a class="dropdown-item" asp-controller="Home" asp-action="Index">Подменю 2</a></li></ul></li></ul><div class="row m-0 me-3 p-0 rounded-pill border border-1 border-secondary-subtle"><div class="col m-0 ms-1 p-1"><i class="fa-solid fa-sun text-secondary" style="padding-top: 3px;"></i></div><div class="col m-0 p-0"><div class="form-check form-switch ms-2 mt-1"><input class="form-check-input" type="checkbox" name="theme" @oninput="changeThreme" @bind="isChecked"  role="switch"></div></div><div class="col m-0 me-1 p-1"><i class="fa-solid fa-moon text-secondary" style="padding-top: 3px;"></i></div></div><div class="d-flex"><a href="https://e-organisation.uni-ruse.bg/People/Person?username=@accessor.HttpContext.User.Identity.Name.Substring(9)" target="_blank" class="person-card card text-decoration-none"><div class="card-body row m-0 p-0"><div class="col-2 m-0 p-0"><div class="person-avatar m-1" style="                                        background: lightgray center center no-repeat;                                        background-size: cover;                                        display: block;                                        position: relative;                                        width: 35px;                                        height: 35px;                                        border-radius: 50%;                                        background-image: url('@bg');"></div></div><div class="col-10 m-0 p-0"><p class="person-names m-1 ms-1 pt-1">@names</p></div></div></a></div></div></div></nav>@code {    // Internal field holding checkbox state    private bool isChecked { get; set; }    const string e_organisation_url = "";    const string e_organisation_api_url = "";    string username = "";    private string bg { get; set; }    string names = "";    private async void changeThreme()    {        if (isChecked == false){            isChecked = true;            await JS.InvokeVoidAsync("eval", $"document.documentElement.setAttribute('data-bs-theme', 'dark')");            await LocalStorage.SetItemAsStringAsync("theme", "dark");        }        else if(isChecked ==  true){            isChecked = false;            await JS.InvokeVoidAsync("eval", $"document.documentElement.setAttribute('data-bs-theme', 'light')");            await LocalStorage.SetItemAsStringAsync("theme", "light");        }    }    protected override async Task OnInitializedAsync()    {        username = accessor.HttpContext.User.Identity.Name.Substring(9);        try        {            using HttpClientHandler handler = new()                {                    UseDefaultCredentials = true,                    PreAuthenticate = true,                    Credentials = CredentialCache.DefaultNetworkCredentials                };            // HttpClient with the configured handler            using HttpClient httpClient = new(handler);            // Call API and get person object data            HttpResponseMessage httpResponse = await httpClient.GetAsync($"{e_organisation_api_url}Person/{username}/Data");            httpResponse.EnsureSuccessStatusCode();            var json = await httpResponse.Content.ReadAsStringAsync();            dynamic personData = Newtonsoft.Json.Linq.JObject.Parse(json);            bg = $"{e_organisation_url}uploads/avatars/{personData.avatar}";            names = personData.personNames;        }        catch (Exception ex)        {            // Handle exceptions here, log them, display an error message, etc.            Console.WriteLine($"An error occurred: {ex.Message}");        }    }}

I tried to create a local variable and the result was the same. Maybe i should do some Utility class idk. I am using Visual Studio 2022.FIXED: using AuthenticationStateProvider instead HttpContextAccessor in my razor pages.


Viewing all articles
Browse latest Browse all 4840

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>