Blazor 与 HttpContextAccessor 的热重载问题

问题描述 投票:0回答:1

当我启动我的应用程序时,它工作正常,但是当我更改某些内容并保存它(在哪个组件中无关紧要)时,热重载无法按预期工作,它说:

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

正如我所见,问题出在 HttpContextAccessor 上。据我所知,它可以工作或请求响应,也许这就是为什么它不能与热重载正常工作的原因。也许我应该做某种存储并将其存储在变量中,或者有没有办法改变 HotReload 的工作原理?

这是我的 NavMenu 组件:

@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}");
        }
    }
}

我尝试创建一个局部变量,结果是一样的。也许我应该做一些实用类idk。我正在使用 Visual Studio 2022。

asp.net blazor .net-8.0
1个回答
0
投票

只需更改框架并使用 PHP 即可。在过去 10 年里,我在各种项目中使用 PHP 都没有遇到任何问题。

© www.soinside.com 2019 - 2024. All rights reserved.