我对这个问题感到非常难过和愚蠢,因为它对许多专家来说看起来很简单,但是这使我无休止地工作了几天,而我的解决方案却无法正常工作,这有点令人沮丧。我们将不胜感激,帮助我摆脱困境。代码链接在本文的结尾。我需要解决的是在Blazor CRUD应用程序中使用授权的方法,以便已登录的用户只能查看特定于他们的数据(由他们在登录后创建的数据)。
什么是项目?我创建了一个分配提醒列表(针对学生),其子组件“ AssignmentDetail”嵌套在名为“ AssignmentReminderList”的父组件中。子组件:具有启用输入数据的形式(作为模态),并显示分配列表:
父组件代码的重要部分:
@if (assignmentList == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Assignments</th>
<th>Status</th>
<th>Due Date</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
@foreach (var assignment in assignmentList)
{
<tr>
<td>@assignment.Title</td>
<td>@assignment.Status</td>
<td>@assignment.DueDate</td>
<td><input type="button" class="btn btn-primary" @onclick="(()=>PrepareForEdit(assignment))" data-toggle="modal" data-target="#assignmentModal" value="Edit" /></td>
<td><input type="button" class="btn btn-primary" @onclick="(()=>PrepareForDelete(assignment))" data-toggle="modal" data-target="#confirmDeleteModal" value="Delete" /></td>
</tr>
}
</tbody>
</table>
}
<div>
<input type="button" data-toggle="modal" data-target="#assignmentModal" class="btn btn-primary" value="Add Task"
@onclick="(()=>InitializeAssignmentObject())" />
</div>
<ConfirmDelete OnClick="@Delete"></ConfirmDelete>
<AssignmentDetail AssignmentObject="assignmentObject" OnSave="@Refreshed">
<CustomHeader>@customHeader</CustomHeader>
</AssignmentDetail>
@code {
List<AssignmentReminder> assignmentList;
AssignmentReminder assignmentObject = new AssignmentReminder();
string customHeader = string.Empty;
private readonly ApplicationDbContext _db;
protected override async Task OnInitializedAsync()
{
assignmentList = await service.GetAssignments();
await GetUserDetails();
}
string Message = "";
public List<AssignmentReminder> AssignmentReminders { get; set; }
private async Task GetUserDetails()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
//if (user.Identity.IsAuthenticated)
//{
var currentUser = await UserManager.GetUserAsync(user);
var currentUserId = currentUser.Id;
assignmentList = await _db.assignments.Where(a => a.OwnerID == currentUserId).ToListAsync();
}
}
型号是:
public class AssignmentReminder
{
[Key]
public int Id { get; set; }
//User ID from AspNetUser table
public string OwnerID { get; set; }
[Required(ErrorMessage = "Assignment title is required")]
[StringLength(50, ErrorMessage = "Title is too long.")]
public string Title { get; set; }
[Required(ErrorMessage = "Status is required")]
public string Status { get; set; }
[Required(ErrorMessage = "Due Date is required")]
public DateTime DueDate { get; set; }
}
现在问题是,我创建的用于过滤并获取特定于用户的数据的GetUserDetails()方法最终在运行时Null Reference Exception中终止,因为我无法找到一种方法来填充OwnerId(在赋值中在分配表中创建记录时,该表与AspNetUser表中的userId相同。
该项目位于:https://github.com/krchome/BlazorAssignmentReminder(适用于希望在年底试用的任何人)
在我看来,问题在于您在创建新记录时没有保存当前用户。