Несколько провайдеров профиля - PullRequest
3 голосов
/ 12 августа 2010

У меня есть несколько поставщиков профилей и типов профилей:

ProviderA с ProfileA
и
ProviderB с ProfileB

Они оба используют разные базы данных. Я хочу иметь возможность сказать:

ProfileB.Create(...), и профиль создается в базе данных B, тогда как ProfileA.Create(...) создает профиль в базе данных A.

Как, черт возьми, я могу настроить это в моем файле web.config?

Следующее (конечно) недействительно:

    <profile inherits="ProfileA, Authenticatie" defaultProvider="ProfileProviderA" enabled="true" automaticSaveEnabled="true">
        <providers>
            <add name="ProfileProviderA" applicationName="websiteA" type="ProfileProviderA, Authenticatie" connectionStringName="connstringA" description=""/>
        </providers>
    </profile>
    <profile inherits="ProfileB, Authenticatie" defaultProvider="ProfileProviderB" enabled="true" automaticSaveEnabled="true">
        <providers>
            <add name="ProfileProviderB" applicationName="websiteB" type="ProfileProviderB, Authenticatie" connectionStringName="connstringB" description=""/>
        </providers>
    </profile>

Ответы [ 2 ]

3 голосов
/ 20 сентября 2010

Я решил эту проблему с несколькими профилями и провайдерами, используя следующий метод взлома:

Первый: создайте базовый класс для ваших профилей.Он не должен содержать все поля;просто важно, чтобы они использовали один и тот же базовый класс (я назвал это CustomProfileBase).

Кроме того, в конфигурации указано следующее изменение:

app.config

<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().

0 голосов
/ 17 сентября 2010

Вы не можете иметь более одного профиля в web.config, но в профиле может быть несколько провайдеров, поэтому, возможно, вам следует задуматься об изменении вашей архитектуры, чтобы иметь только один профиль, возможно, даже смешивая их вместе. Тогда у вас будет такой вид web.config:

<profile inherits="ProfileA" defaultProvider="ProfileProviderA" enabled="true" automaticSaveEnabled="true">
    <providers>
        <add name="ProfileProviderA" applicationName="websiteA" type="ProfileProviderA, Authenticatie" connectionStringName="connstringA" description=""/>
        <add name="ProfileProviderB" applicationName="websiteB" type="ProfileProviderB, Authenticatie" connectionStringName="connstringB" description=""/>
    </providers>
    <properties>
        <clear/>
        <add name="property1" type="type1" provider="ProfileProviderA" />
        <add name="property2" type="type2" provider="ProfileProviderB" />
    </properties>
</profile>

Другое решение состоит в том, чтобы разделить ваш сайт на 2 подкаталога / подприложения на основе ваших профилей и создать в каждом подпапке собственный файл web.config с нужным профилем.

...