Blazor Server App 组件突然抛出空引用异常

问题描述 投票:0回答:3
今天,我几周来每天开发的 Blazor 服务器应用程序突然开始在 _Host.cshtml 中抛出异常,当我在 Visual Studio 2022 中以调试模式启动它时。错误如附图所示。

enter image description here

_Host.cshtml 的当前状态

@page "/" @namespace Ano.Blazor.Pages @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @{ Layout = "_Layout"; } <component type="typeof(App)" render-mode="ServerPrerendered" /> <link rel="stylesheet" href="_content/Radzen.Blazor/css/standard-base.css"/> <script src="_content/Radzen.Blazor/Radzen.Blazor.js"></script>
这是 App.razor,该组件似乎在 _Host.cshtml 中抛出异常

<CascadingAuthenticationState> <Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"> <NotAuthorized> <Ano.Blazor.Pages.RedirectToLogin></Ano.Blazor.Pages.RedirectToLogin> </NotAuthorized> </AuthorizeRouteView> <FocusOnNavigate RouteData="@routeData" Selector="h1" /> </Found> <NotFound> <PageTitle>Not found</PageTitle> <LayoutView Layout="@typeof(MainLayout)"> <p role="alert">Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router> </CascadingAuthenticationState>
奇怪的是,当异常第一次出现时,我没有对 _Host.cshtml 或 App.razor 进行任何更改。  我刚刚所做的是为身份添加脚手架项目,特别是ConfirmEmail razor 页面。

昨天添加了 Radzen 组件的使用,并且没有引起任何问题。 但为了排除这种情况,我尝试运行应用程序并删除对 Radzen css 和 js 的引用。 异常仍然存在。

此时我已经梳理了解决方案中的每个文件,寻找可能导致此问题的任何内容。 该应用程序构建和重建没有错误。 该异常并没有告诉我问题可能出在哪里。

为了进行比较,我将之前的推送克隆到一个单独的文件夹,在 VS 2022 的新实例中启动该解决方案,在调试模式下运行该应用程序并正常启动。 这让我想到也许解决方案本身就有问题。 损坏了? 我删除了 .vs 文件夹并允许原始解决方案重新创建它,但之后异常仍然存在。

有人见过这个问题吗?

blazor
3个回答
12
投票
问题是我不小心创建了两个具有相同@page指令的页面。

EditUser.razor 有这个指令...

@page "EditUser{id}"
EditMyAccount.razor 有相同的指令...

@page "EditUser{id}"
我更改了 EditMyAccount.razor 以具有此指令...

@page "EditMyAccount"
这解决了运行时问题。

在我看来,这个问题太难找到了,因为 Visual Studio 没有任何编译警告或运行时异常来提供页面指令的线索。 希望这将来能对其他人有所帮助。


1
投票
您的路线中的任何问题似乎都会导致此错误。我试图绑定查询字符串参数(“/{parameter}?{variable}”)并收到相同的错误。


0
投票
类似的问题。真正的原因是相当间接的。 我已向 Blazor 应用程序添加了一项新服务,但未将其添加到 Startup.cs 中

例如在我的 Startup.cs 中,我需要:

services.AddTransient<ICityOrZipLookupService, CityOrZipLookupService>();
空异常没有明显的关系,因为注入以相当隐藏的方式发生。
在我的自定义组件中:

public partial class EnterCityOrZipInput : ComponentBase { [Inject] public ICityOrZipLookupService CityOrZipLookupService { get; init; } = default!; ... etc ...
    
© www.soinside.com 2019 - 2024. All rights reserved.