代码之家  ›  专栏  ›  技术社区  ›  jason

更改ASP.NET标识提供程序的连接字符串

  •  0
  • jason  · 技术社区  · 6 年前

    我有一个使用ClaimSidentity的WebForms应用程序(不是MVC)。我希望动态地切换连接字符串,但我看不到这样做的方法。我在网上看到的所有关于MVC的参考资料。这是我的代码:

    Dim userStore As New UserStore(Of IdentityUser)
    Dim roleStore As New RoleStore(Of IdentityRole)
    Dim userManager As New UserManager(Of IdentityUser)(userStore)
    Dim roleManager As New RoleManager(Of IdentityRole)(roleStore)
    
    Dim userName As String = identity.Claims.First(Function(claim) claim.Type = ClaimTypes.WindowsAccountName).Value 
    

    是否仍要更改正在使用的连接字符串,而不是在web.config文件中找到的默认连接字符串?

    编辑

    我试着创建这个类,其来源是:

    Imports System.Data.Entity
    Imports Application.Common
    Imports Application.Data.Migrations
    Imports Application.Models
    Imports Microsoft.AspNet.Identity.EntityFramework
    
    Namespace Application.Data
        Public Class ApplicationDbContext
            Inherits IdentityDbContext(Of IdentityUser)
    
            Public Sub New(ByVal stringName As String)
                MyBase.New(stringName, throwIfV1Schema:=False)
            End Sub
    
    
            Public Shared Function Create(ByVal stringName As String) As ApplicationDbContext
                Return New ApplicationDbContext(stringName)
            End Function
    
            Public Overloads Function [Set](Of TEntity As Class)() As IDbSet(Of TEntity)
                Return MyBase.[Set](Of TEntity)()
            End Function
        End Class
    End Namespace
    

    然后,我这样做:

    Dim newContext As ApplicationDbContext = New ApplicationDbContext("test")
    
    Dim userStore As New UserStore(newContext)
    Dim roleStore As New RoleStore(newContext)
    Dim userManager As New UserManager(Of IdentityUser)(userStore)
    Dim roleManager As New RoleManager(Of IdentityRole)(roleStore)
    

    但是,变量userstore和rolestore的一个错误“到很少的争论到‘userstore’…”

    编辑

    创建这样的管理者是有效的:

     Dim userStore = New UserStore(Of IdentityUser)(New ApplicationDbContext("DefaultConnection1"))
     Dim roleStore = New RoleStore(Of IdentityRole)(New ApplicationDbContext("DefaultConnection1"))
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Kahbazi    6 年前

    您可以创建一个 IdentityDbContext 实例并通过构造函数设置connectionString,然后创建 UserStore RoleStore 并最终使用它们来创建 UserManager RoleManager .

    我不太擅长 VB 我的意思是 C#

    string nameOrConnectionString = "YOUR_CONNECTION_STRING";
    var dbcontext = new IdentityDbContext(nameOrConnectionString);
    
    var userStore = new UserStore(dbcontext);
    var roleStore = new RoleStore(dbcontext);
    
    var UserManager = new UserManager(roleStore);
    var RoleManager = new RoleManager(roleStore);