[ASP.NET]執行時期,修改ProfileProvider的Connection String
我們有個Web AP是使用SqlProfileProvider,ConnectionString是定義在web.config之中,但是如果是要執行時,改變它的ConnectionString,要如何做呢?
參考Setting Membership/Profile/Role provider's connection string at runtime...?
1.建立DLL專案,加入System.Web及System.configuration參考
2.繼承SqlProfileProvider,然後覆寫Initialize Method,然後修改_sqlConnectionString的屬性值,如下,
using System;
using System.Reflection;
namespace CustomizeProvider
{
public class ProfileProvider : System.Web.Profile.SqlProfileProvider
{
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
base.Initialize(name, config);
// 執行時期,更新ProfileProvider的Connection String
string connectionString = @"Your new connection string";
// Set private property of Membership provider.
FieldInfo connectionStringField = GetType().BaseType.GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
connectionStringField.SetValue(this, connectionString);
}
}
}
3.修改web.config改執行自定的Provider,如下,
<profile enabled="true" automaticSaveEnabled="false" defaultProvider="DashboardProfileSqlProvider" inherits="UserProfile">
<providers>
<clear />
<add name="DashboardProfileSqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="DashboardConnectionString" applicationName="Dashboard" description="SqlProfileProvider for Dashboard" />
</providers>
<properties>
<add name="PageSize" type="Integer" />
</properties>
</profile>
改成
<profile enabled="true" automaticSaveEnabled="false" defaultProvider="DashboardProfileSqlProvider" inherits="UserProfile">
<providers>
<clear />
<add name="DashboardProfileSqlProvider" type="CustomizeProvider.ProfileProvider" connectionStringName="DashboardConnectionString" applicationName="Dashboard" description="CustomizeProvider for Dashboard" />
</providers>
<properties>
<add name="PageSize" type="Integer" />
</properties>
</profile>
範例程式:
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^