strong-typed profile values in ASP.NET membership

2019-03-02 15:02发布

问题:

I've been using ASP.NET MVC with membership-based login for several years and everything is working fine (it's now MVC3, but membership didn't change since the first version which was MVC1). Now I need to add a value into the profile (just one value, of very seldom use - so it doesn't warrant custom membership provider or custom tables)

I got it working through profile.SetPropertyValue("myprop"), but I would really want to get profile.myprop to work. Is it possible?

I saw some advise to have a custom class MyProfile : ProfileBase and have myprop as a property of that class. For some reason, casting ProfileBase.Create(currentUser.UserName) to MyProfile gives me an error (illegal cast).

Is there an example somewhere of ASP MVC application with Profile, similar to this Old Post by ScottGu?

回答1:

Joel Spolsky had a great answer to this question on this post. You're basically on the right track.

If you're getting the illegal cast error, its most likely due to a problem in the config file. Make sure this is included; more specifically the <profile defaultProvider="SqlProvider" inherits="YourNamespace.AccountProfile"> section.

<profile defaultProvider="SqlProvider" inherits="YourNamespace.AccountProfile">
    <providers>
         <clear />
         <add name="SqlProvider"
              type="System.Web.Profile.SqlProfileProvider"
              connectionStringName="sqlServerMembership" />
    </providers>
</profile>