Razor组件GetFromJsonAsync报System.NullReferenceException问题求助
Blazor页面加载新增Booking条目时抛出NullReferenceException异常
我是FullStack开发的学生,做实验时碰到老师也解决不了的错误。页面能创建并显示条目,但刷新查看新增条目时出现加载错误,开发者工具显示抛出System.NullReferenceException异常,不过该条目仍能在Visual Studio的数据表里正常查看。
错误指向Index.razor第37行的代码:
protected async override Task OnInitializedAsync() { Bookings = await _client.GetFromJsonAsync<List<Booking>>($"{Endpoints.BookingsEndpoint}"); }
完整的Index.razor代码如下:
@page "/bookings/" @inject HttpClient _client @inject IJSRuntime js @attribute [Authorize] <h3 class="card-title">Car Bookings</h3> <br /> <a href="/bookings/create" class="btn btn-secondary"> <span class="oi oi-plus"></span> Create New Booking </a> <br /> <br /> @if (Bookings == null) { <div class="alert alert-info">Loading Bookings...</div> } else { <table class="table table-responsive"> <thead> <tr> <th>Booking Id</th> <th>Customer License</th> <th>Date</th> <th>Duration in days</th> <th>Plate Number</th> <th>Actions</th> </tr> </thead> <tbody> @foreach (var booking in Bookings) { <tr> <td>@booking.Id</td> <td>@booking.CustomerId</td> <td>@booking.DateCreated.Date.ToString("dd/mm/yyyy")</td> <td>@(booking.DateIn != nullDT ? (booking.DateIn - booking.DateOut).TotalDays.ToString() : "To Be Determined")</td> <td>@booking.Vehicle.LicensePlateNumber</td> <td> <a href="/bookings/view/@booking.Id" class="btn btn-primary"> <span class="oi oi-book"></span> </a> <a href="/bookings/edit/@booking.Id" class="btn btn-warning"> <span class="oi oi-pencil"></span> </a> <button class="btn btn-danger" @onclick="@(()=>Delete(booking.Id))"> <span class="oi oi-delete"></span> </button> </td> </tr> } </tbody> </table> } @code { private List<Booking> Bookings; private DateTime nullDT = new DateTime(1, 1, 1, 0, 0, 0); protected async override Task OnInitializedAsync() { Bookings = await _client.GetFromJsonAsync<List<Booking>>($"{Endpoints.BookingsEndpoint}"); } async Task Delete(int bookingId) { var booking = Bookings.First(q => q.Id == bookingId); var confirm = await js.InvokeAsync<bool>("confirm", $"Do you want to delete {booking.Id}?"); if (confirm) { await _client.DeleteAsync($"{Endpoints.BookingsEndpoint}/{bookingId}"); await OnInitializedAsync(); } } }
补充Booking类代码:
using System; namespace CarRentalManagement.Shared.Domain { public class Booking:BaseDomainModel { public DateTime DateOut { get; set; } public DateTime DateIn { get; set; } public int VehicleId { get; set; } public virtual Vehicle Vehicle { get; set; } public int CustomerId { get; set; } public virtual Customer Customer { get; set; } } }
解决思路
- 检查API是否加载关联实体:异常大概率是因为
booking.Vehicle为null,后端API返回Booking列表时,需要确保用EF Core的.Include(b => b.Vehicle)加载关联的Vehicle实体,否则Vehicle属性会是null。 - 验证新增Booking的VehicleId有效性:新增时确认传入的VehicleId对应数据库中存在的Vehicle记录,无效的Id会导致Vehicle关联对象为null。
- 添加空值安全访问:在页面中修改
@booking.Vehicle.LicensePlateNumber为@(booking.Vehicle?.LicensePlateNumber ?? "无"),避免直接访问null对象的属性。 - 检查API返回内容:用浏览器Network标签查看Bookings接口的返回JSON,确认Vehicle字段是否为null,或者返回格式是否正确。
- 初始化空列表:在@code中将
private List<Booking> Bookings;改为private List<Booking> Bookings = new List<Booking>();,避免页面渲染时的潜在空值问题。
内容的提问来源于stack exchange,提问作者BorisLimTP
相关产品推荐
相关产品推荐

