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

使用ASP.NET Core Identity 8.0.6接口时遇JSON请求解析错误

解决Login/Register接口JSON读取失败的问题

问题根源

错误提示明确指向请求体无法解析为有效JSON,结合你的配置代码,核心原因是Identity服务配置不完整+中间件顺序错误,同时Swagger测试时的请求格式也需要注意。

修复步骤

1. 补全Identity依赖的实体类

Identity运行需要自定义用户类和数据库上下文类,你当前的代码缺少这两个核心组件:

// ApplicationUser.cs - 自定义用户实体
public class ApplicationUser : IdentityUser
{
    // 可根据需求添加自定义字段,如昵称、头像地址等
}

// ApplicationDbContext.cs - 数据库上下文
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
    }
}

2. 修正Identity服务配置

原代码中AddIdentityCore和AddDbContext缺少泛型参数,导致Identity无法正确绑定数据存储,修改如下:

// 替换原AddDbContext代码
builder.Services.AddDbContext<ApplicationDbContext>(
    options => options.UseSqlServer("Server=DESKTOP-EI90NJF\\SQLEXPRESS;User Id=WebChatUser;Password=Password123;Database=WebChat")
);

// 替换原AddIdentityCore代码
builder.Services.AddIdentityCore<ApplicationUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddApiEndpoints();

3. 调整中间件顺序

身份验证中间件必须在授权中间件之前执行,同时移除无效的空UseMiddleware()调用:

// 调整后的中间件顺序
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseCors(myAllowSpecificOrigins);

app.UseHttpsRedirection();

app.UseAuthentication(); // 新增这行,放在UseAuthorization之前
app.UseAuthorization();

4. Swagger测试规范

在Swagger UI中测试时必须满足以下要求:

  • 请求方法选择POST(Login/Register接口均为POST类型)
  • 在Body标签下选择raw,并将Content-Type设置为application/json
  • 输入符合格式的JSON请求体,例如Login请求示例:
{
  "email": "test@example.com",
  "password": "YourPassword123!"
}

修正后的完整核心配置代码

var myAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: myAllowSpecificOrigins,
        policy => {
            policy.AllowAnyMethod()
                  .AllowAnyHeader()
                  .SetIsOriginAllowed(origin => true)
                  .AllowCredentials();
        });
});

// 注册自定义单例服务
builder.Services.AddSingleton<IDictionary<string, UserConnection>>(opts => new Dictionary<string, UserConnection>());
builder.Services.AddSingleton<IDictionary<string, ChatRoom>>(opts => new Dictionary<string, ChatRoom>());

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSignalR();

// 修正DbContext配置
builder.Services.AddDbContext<ApplicationDbContext>(
    options => options.UseSqlServer("Server=DESKTOP-EI90NJF\\SQLEXPRESS;User Id=WebChatUser;Password=Password123;Database=WebChat")
);

// 修正Identity配置
builder.Services.AddIdentityCore<ApplicationUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddApiEndpoints();

builder.Services.AddAuthentication().AddBearerToken(IdentityConstants.BearerScheme);
builder.Services.AddAuthorizationBuilder();

var app = builder.Build();

app.UseDefaultFiles();
app.UseStaticFiles();
app.UseCors(myAllowSpecificOrigins);

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapHub("/chatHub");
app.MapFallbackToFile("/index.html");
app.MapIdentityApi<ApplicationUser>(); // 绑定自定义用户类型
app.MapControllers();

app.Run();

内容的提问来源于stack exchange,提问作者Pedro Figueiredo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 11:40:10