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

在ASP.NET Core 2中间件中注入SignInManager与AspNetUserManager

解决刷新令牌中间件注入SignInManager与UserManager的问题

嘿,我之前在做Web API的刷新令牌逻辑时,刚好也碰到过类似的Identity服务注入问题,结合你的场景(ApplicationUser继承IdentityUser<int>),给你梳理几个关键的解决步骤:

1. 先确认Identity服务已正确注册

SignInManager和UserManager都是Identity框架提供的服务,必须先在Program.cs(.NET 6+)或Startup.cs的ConfigureServices方法中完成注册,才能被注入到中间件里。一定要指定你的自定义用户类型和主键类型(这里是int):

// Program.cs 示例代码
builder.Services.AddIdentity<ApplicationUser, IdentityRole<int>>()
    .AddEntityFrameworkStores<MyDataContext>() // 替换成你的DbContext实现
    .AddDefaultTokenProviders();

注:你提到的AspNetUserManager<ApplicationUser>其实就是UserManager<ApplicationUser>的默认实现,框架会自动注册,直接注入UserManager<ApplicationUser>即可。

2. 调整中间件构造函数的注入方式

因为SignInManager和UserManager都是Scoped生命周期的服务,不需要用工厂模式(比如你之前的Func<IMyDataContext>),直接在构造函数中注入就行:

private readonly RequestDelegate _next;
private readonly AuthService _service;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;

public TokenProviderMiddleware(RequestDelegate next, AuthService service, 
    SignInManager<ApplicationUser> signInManager, 
    UserManager<ApplicationUser> userManager)
{
    _next = next;
    _service = service;
    _signInManager = signInManager;
    _userManager = userManager;
}

3. 注意中间件的注册顺序

一定要把你的刷新令牌中间件放在身份验证中间件之后,这样才能保证Identity服务已经初始化完成:

// Program.cs 中间件注册部分
app.UseAuthentication();
app.UseMiddleware<TokenProviderMiddleware>(); // 你的刷新令牌中间件
app.UseAuthorization();

4. 解决常见的注入错误

如果遇到“无法解析服务类型”的报错,大概率是这两个原因:

  • 忘记在服务注册时指定主键类型(默认是string,而你的ApplicationUser用的是int)
  • 错误地用单例模式注册了中间件,导致Scoped生命周期的SignInManager/UserManager无法被解析(必须用app.UseMiddleware<T>来注册中间件)

备选方案:在InvokeAsync方法中获取服务

如果你不需要在构造函数中初始化这些服务,只在请求处理时用到,也可以通过HttpContext的RequestServices来动态获取:

public async Task InvokeAsync(HttpContext context)
{
    var signInManager = context.RequestServices.GetRequiredService<SignInManager<ApplicationUser>>();
    var userManager = context.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();
    
    // 这里编写你的刷新令牌逻辑
    await _next(context);
}

内容的提问来源于stack exchange,提问作者Matthew Flynn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:12:44