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

AspNetIdentity 2.2.2代码移至DLL后无法获取ApplicationUserManager问题

解决ASP.NET WebForms DLL中获取ApplicationUserManager为空的问题

问题根源

将IntranetSecurity.vb移至独立DLL后,直接调用Context.GetOwinContext().GetUserManager(Of ApplicationUserManager)()返回空值,核心原因:

  • DLL中的全局Context并非当前请求的HttpContext,无法获取网站项目中注册的Owin上下文
  • ApplicationUserManager多为网站项目自定义类型,DLL可能无法正确识别或访问该类型

解决方案(保留原初始化接口)

1. 利用传入的Page对象获取当前请求上下文

原构造函数已传入Page实例,直接通过该实例的Context获取Owin上下文,进而拿到ApplicationUserManager。修改IntranetSecurity类的构造函数及内部逻辑:

Public Class IntranetSecurity
    Private ReadOnly _userManager As ApplicationUserManager
    Private ReadOnly _appName As String

    Public Sub New(page As Page, appName As String)
        _appName = appName
        
        ' 通过传入的Page获取当前请求的Owin上下文
        Dim owinCtx = page.Context.GetOwinContext()
        _userManager = owinCtx.GetUserManager(Of ApplicationUserManager)()

        ' 空值校验,避免后续业务逻辑报错
        If _userManager Is Nothing Then
            Throw New InvalidOperationException("无法获取ApplicationUserManager,请检查网站Owin及Identity配置")
        End If
    End Sub

    ' 示例业务方法:使用获取到的UserManager
    Public Function GetCurrentUserId() As String
        Return _userManager.FindById(page.Context.User.Identity.GetUserId())?.Id
    End Function
End Class

2. 确保ApplicationUserManager类型可被DLL访问

如果ApplicationUserManager是网站项目内的自定义类,需将其迁移至共享类库(可与IntranetSecurity同属一个DLL,或单独新建共享类库),让所有80+网站项目和IntranetSecurity所在DLL都引用该共享类库,避免类型无法识别的问题。

3. 验证网站项目的Owin配置正确性

确保所有网站项目的Owin启动类中正确注册ApplicationUserManager:

Public Class Startup
    Public Sub Configuration(app As IAppBuilder)
        ' 注册ApplicationUserManager到Owin上下文
        app.CreatePerOwinContext(AddressOf ApplicationUserManager.Create)
        ' 其他Owin配置(如Cookie认证等)
    End Sub
End Class

同时检查网站Web.config的appSettings中是否配置了正确的Owin启动类:

<appSettings>
    <add key="owin:AppStartup" value="YourNamespace.Startup" />
</appSettings>

4. 统一Identity包版本

确保IntranetSecurity所在DLL和所有网站项目引用的Microsoft.AspNet.Identity.Core版本一致(均为2.2.2),避免版本兼容性导致的上下文获取失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:40:16