如果我使用 OnInitializedAsync 方法,页面初始化时出现 NullReferenceException

NullReferenceException on page initialization if I use OnInitializedAsync method

我有一个简单的应用程序,但它在页面初始化时停止工作并出现错误

NullReferenceException: 对象引用未设置到对象的实例。 Site.Shared.MainLayout.BuildRenderTree(RenderTreeBuilder __builder) 错误: enter image description here

但是代码并不复杂。 App.razor:

<Router AppAssembly="@typeof(Program).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
    </Found>
  <NotFound>
      <LayoutView Layout="@typeof(MainLayout)">
          <p>Sorry, there's nothing at this address.</p>
      </LayoutView>
  </NotFound>

_Host.cshtml: enter image description here

MainLayout.razor: enter image description here

StartUpService.cs: enter image description here

page.GetPageGlobalAsync() 运行良好,我可以在调试模式下通过此方法。 enter image description here

但是在我出现这个错误之后。并且不知道是什么原因以及如何获得有关错误的更多信息。

UPD

如果我将代码更改为:

PageGlobal page =  new PageGlobal()

它开始工作了,但是 OnInitializedAsync 是异步方法,为什么我不能在 OnInitializedAsync 方法中使用异步等待方法?

您的页面甚至在从异步方法获取它之前就试图呈现 @pageGlobal.Title。这就是为什么如果你这样做 pageGlobal = new PageGlobal(); 它不会崩溃。

改成这样:

<div class="top-row h3">
    @if(pageGlobal != null)
    {
        pageGlobal.Title
    }
</div>

或者如果你想要一个衬垫:

<div class="top-row h3">
    @pageGlobal?.Title
</div>

不建议在进行 Async 编程时使用 Task.Run。尝试在 GetPageGlobalAsync 中使用 Task.FromResult 而不是 Task.Run

 public async Task<PageGlobal> GetPageGlobalAsync()
    {
        return await Task.FromResult( new PageGlobal());
    }