You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET8 Blazor+Microsoft Identity用户头像上传及DbContext问题排查

.NET8 Blazor 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 20:56:36