.NET8 Blazor+Microsoft Identity用户头像上传及DbContext问题排查
背景
使用Visual Studio 2022 Preview模板创建基于.NET8框架和Blazor的网站,已在ApplicationUser中添加新属性ProfilePicture,定义如下:
public byte[]? ProfilePicture { get; set; }
需在Components > Pages > Account > Manage下的Index.razor中实现用户头像上传功能。
初始问题
在HTML部分添加代码:
<InputFile OnChange="LoadFiles" />
及对应逻辑:
private async Task LoadFiles(InputFileChangeEventArgs e) { MemoryStream ms = new MemoryStream(); await e.File.OpenReadStream().CopyToAsync(ms); var bytes = ms.ToArray(); _user.ProfilePicture = bytes; await UserManager.UpdateAsync(_user); Input.ProfilePicture = bytes; }
但选择图片时LoadFiles函数未触发,设置RenderModeInteractiveAuto渲染页面会报错。
更新1:新建上传页面后的跟踪冲突错误
创建新Razor页面用于上传头像(移除非关键代码):
@using BlazorIdentity.Data @using Microsoft.AspNetCore.Identity @rendermode RenderMode.InteractiveServer @inject AuthenticationStateProvider AuthenticationStateProvider @inject UserManager<ApplicationUser> UserManager <InputFile OnChange="LoadFiles" /> @code { [Parameter] public ApplicationUser? User { get; set; } = default!; private async Task LoadFiles(InputFileChangeEventArgs e) { MemoryStream ms = new MemoryStream(); await e.File.OpenReadStream().CopyToAsync(ms); var bytes = ms.ToArray(); User.ProfilePicture = bytes; await UserManager.UpdateAsync(User); } }
执行UpdateAsync时出现错误:
System.InvalidOperationException: The instance of entity type 'ApplicationUser' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
未修改ID,仅更改ApplicationUser的属性值。
更新2:页面跳转时的DbContext并发错误
Identity页面使用VS2022 Preview模板,仅添加新字段。但点击菜单跳转页面时未做任何修改就出现错误:
A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext.
内容的提问来源于stack exchange,提问作者Enrico

