如何在运行时为不同的角色和成员资格提供程序编辑app.config

时间:2017-02-06 09:58:06

标签: app-config

我正在开发Visual Studio 2015中的vb.net开发项目,并且需要能够在运行时编辑项目的app.config,以便访问不同网站的角色和成员资格提供程序。我希望能够更改 connectionStrings 部分中的 ApplicationServices 设置以及成员资格和角色管理器提供程序中的 applicationName 设置/ strong>部分。我已经编辑了项目基本目录中的初始 app.config 文件,如下所示:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
      </startup>
      <connectionStrings>
        <clear />
        <add name="ApplicationServices" connectionString="Data Source=.\SQLEXPRESS; Integrated Security=True; User Instance=False; Connect Timeout=30; Initial Catalog=MYWEBSITE" providerName="System.Data.SqlClient" />
      </connectionStrings>
      <system.web>
        <membership>
          <providers>
            <clear />
            <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" applicationName="/" passwordFormat="Encrypted" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="true" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="8" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="5" />
          </providers>
        </membership>
        <roleManager enabled="true">
          <providers>
            <clear />
            <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
            <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
          </providers>
        </roleManager>
      </system.web>
    </configuration>

在运行时,我尝试使用以下代码从上面显示的项目 app.config 文件中获取设置:

            Public Shared Function ReadAllConfigSettings(ByRef Configs(,) As String) As Boolean
        ReadAllConfigSettings = False
        Configs.Initialize()
        Dim ConfigCounter As Integer = 0
        Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        Try
            Dim Settings = config.AppSettings.Settings
            If Settings.Count = 0 Then
                ReadAllConfigSettings = False
                Exit Function
            Else
                For Each key As String In Settings.AllKeys
                    ConfigCounter = ConfigCounter + 1
                    Configs(ConfigCounter, 1) = key
                    Configs(ConfigCounter, 2) = Settings(key).Value
                Next
                ReadAllConfigSettings = True
            End If
        Catch e As ConfigurationErrorsException
            ReadAllConfigSettings = False
        End Try
    End Function

当我运行上面的代码时,从设置= config.AppSettings.Settings 代码行检索到的设置集合始终为空且带有空条目且 Settings.Count 为0。

我很难过为什么我没有将这个设置添加到 app.config 文件中,如果我甚至无法弄清楚如何更改它们,我就无法继续检索它们。有人能指出我正确的方向吗?

谢谢!

大卫

1 个答案:

答案 0 :(得分:0)

在重新思考这个过程之后,我想出了一个解决方案,似乎是一种不用尝试编辑 app.config 文件的方法。下面是我在研究问题时发现的片段中拼写的代码:

            Public Shared Function UpdateMembership(ConnectionStr As String, AppName As String, UserName As String, OldPassword As String, NewPassword As String, TheQuestion As String, TheAnswer As String, Optional TheError As String = Nothing) As Boolean
        UpdateMembership = False
        Dim IsMember As Boolean = False
        Dim AUser As MembershipUser
        Dim ChangePassOK As Boolean = False
        Dim ChangeQAOK As Boolean = False
        Try
            Dim settings As Object = ConfigurationManager.ConnectionStrings("ApplicationServices")
            Dim fi As Object = GetType(ConfigurationElement).GetField("_bReadOnly", (BindingFlags.Instance Or BindingFlags.NonPublic))
            fi.SetValue(settings, False)
            settings.ConnectionString = ConnectionStr
            Membership.Providers.Item("AspNetSqlMembershipProvider").ApplicationName = AppName
            Roles.Providers.Item("AspNetSqlRoleProvider").ApplicationName = AppName
            Roles.Providers.Item("AspNetWindowsTokenRoleProvider").ApplicationName = AppName
            IsMember = Membership.ValidateUser(UserName, OldPassword)
            If IsMember Then
                AUser = Membership.GetUser(UserName, False)
                If Not IsNothing(AUser) Then
                    ChangePassOK = AUser.ChangePassword(OldPassword, NewPassword)
                    If ChangePassOK Then
                        ChangeQAOK = AUser.ChangePasswordQuestionAndAnswer(NewPassword, TheQuestion, TheAnswer)
                    End If
                    If ChangeQAOK Then
                        UpdateMembership = True
                    End If
                End If
            End If
        Catch ex As Exception
            If Not IsNothing(TheError) Then
                TheError = ex.Message
            End If
        End Try
    End Function

它工作正常,因此可用于调整特定于每个站点配置的任何用户的安全设置。