动态修改配置文件基本连接字符串

本文关键字:连接 字符串 修改 配置文件 动态 | 更新日期: 2023-09-27 18:31:01

我有以下代码,我想用它来修改ProfileBase connectionString:

ProfileBase profile = ProfileBase.Create(username);
string _connectionString = (_DataModel.Connection as System.Data.EntityClient.EntityConnection).StoreConnection.ConnectionString;
FieldInfo connectionStringField = profile.Providers["MySqlProfileProvider"].GetType().BaseType.GetField("_sqlConnectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
connectionStringField.SetValue(profile.Providers["MySqlProfileProvider"], _connectionString);
profile["FirstName"] = firstName;
profile["Surname"] = surname;
profile.Save();

首先,connectionStringField总是返回为空,但是我可以看到profile.Providers确实包含MySqlProfileProvider。这是我Web.Config中指定的:

<profile defaultProvider="MySqlProfileProvider">
  <providers>
    <clear/>
    <add name="MySqlProfileProvider" connectionStringName="MyApp" applicationName="MyApp" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
  </providers>
  <properties>
    <add allowAnonymous="false" defaultValue="" name="FirstName" readOnly="false" serializeAs="String" type="System.String"/>
    <add allowAnonymous="false" defaultValue="" name="Surname" readOnly="false" serializeAs="String" type="System.String"/>
  </properties>
</profile>

我的问题是connectionStringField怎么会以空的形式回来?这是否意味着我无法像通常使用自定义MembershipProvider一样通过重写其Initialize方法来修改连接字符串?

动态修改配置文件基本连接字符串

你往下放了太多的基本类型:

.Providers["MySqlProfileProvider"].GetType()**.BaseType**.GetField
.Providers["MySqlProfileProvider"].GetType().GetField

以下代码应该有效:

string _connectionString = (_DataModel.Connection as System.Data.EntityClient.EntityConnection).StoreConnection.ConnectionString;
Type type = profile.Providers["MySqlProfileProvider"].GetType();
FieldInfo connectionStringField = type.GetField("_sqlConnectionString", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
connectionStringField.SetValue(profile.Providers["MySqlProfileProvider"], _connectionString);