我已经通过多个配置文件和提供者解决了这个问题,使用以下技巧:
首先:为您的配置文件创建一个基类。它不必包含所有字段;重要的是它们共享相同的基类(我称之为 this CustomProfileBase
)。
此外,配置中的以下更改:
应用程序配置
<system.web>
<membership defaultProvider="CustomSqlProviderA" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="CustomSqlProviderA" applicationName="websiteA" type="Authenticatie.A.CustomMembershipProvider, Authenticatie" description="A Membership" connectionStringName="profilesA" />
<add name="CustomSqlProviderB" applicationName="websiteB" type="Authenticatie.B.CustomMembershipProvider, Authenticatie" description="B Membership" connectionStringName="profilesB" />
</providers>
</membership>
<profile inherits="Authenticatie.CustomProfileBase, Authenticatie" defaultProvider="AProfielen" enabled="true">
<providers>
<add name="AProfielen" applicationName="websiteA" type="Authenticatie.A.CustomProfileProvider, Authenticatie" connectionStringName="profielenA" description="A"/>
<add name="BProfielen" applicationName="websiteB" type="Authenticatie.B.CustomProfileProvider, Authenticatie" connectionStringName="profielenB" description="B"/>
</providers>
</profile>
</system.web>
代码
// find the membershipprovider based on the property 'website'
var membershipProvider = Membership.Providers.Cast<MembershipProvider>().Single(s => s.ApplicationName == (website == Website.A ? "websiteA" : "websiteB"));
// find the according profileProvider
var profileProvider = ProfileManager.Providers[website == Website.A ? "AProfielen" : "BProfielen"];
// here's the hacky part. There is a static field on the ProfileManager
// that needs to be set. 'Membership' uses the ProfileManager to retrieve
// and store the profile; so it's pretty much the only way
FieldInfo cPr = typeof(ProfileManager).GetField("s_Provider", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
cPr.SetValue(null, profileProvider);
// Now we can retrieve the current user through our selected membershipProvider
var user = membershipProvider.GetUser(gebruikersData.EmailAdres, false);
if (user == null)
{
// create user:
membershipProvider.CreateUser(mail, password, mail, null, null, true, null, out createStatus);
// create according profile. ProfileBase uses Membership internal.
var profile = (CustomProfileBase)ProfileBase.Create(mail);
// set the default values, you can upcast your profile again
profile.Save();
}
现在我们已经在相应的数据库中创建了一个用户以及一个配置文件。您可以通过 检索用户,membershipProvider
并通过 检索配置文件ProfileManager.FindProfilesByUserName()
。