在简单的 Blazor 应用程序中出现 "Object reference not set to an instance of an object." 错误。我究竟做错了什么?

Getting an "Object reference not set to an instance of an object." error in a simple Blazor app. What am I doing wrong?

我收到以下错误。来自我的 API.

的简单所有记录调用
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
  Unhandled exception rendering component: Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
  at MusicManager.Client.Pages.Themes.BuildRenderTree(RenderTreeBuilder __builder) in
E:\Projects\marklalich\MusicManager\MusicManager\Client\Pages\Themes.razor:line 7
  at Microsoft.AspNetCore.Components.ComponentBase.<.ctor>b__6_0(RenderTreeBuilder builder)
  at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder
  batchBuilder, RenderFragment renderFragment, Exception& renderFragmentException)

这是代码,我做错了什么?

@page "/themes"
@inject IThemeService ThemeService

<div class="container mt-3">
    <h2>Themes</h2>
    <p>asfgasfgasdfgasdfg</p>
    @if (ThemeService.Themes.Count == 0) <== this is the line the error is referencing
    {
        <span>Loading Themes...</span>
    }
    else
    {
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Title</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var theme in ThemeService.Themes)
                {
                    <tr>
                        <td>@theme.Title</td>
                    </tr>
                }
            </tbody>
        </table>
    }
</div>

@code {
    protected override async Task OnInitializedAsync()
    {
        await ThemeService.GetThemes();
    }
}

组件首次渲染时

await ThemeService.GetThemes();

产量。

此时我猜测 ThemeService.Themes 为空,因此没有主题可计算:

@if (ThemeService.Themes.Count == 0)

所以你需要做一个空检查:

@if (ThemeService.Themes is null)

查看 FetchData 页面。