Quick Tip: Getting MembershipProvider for SPWebApplication
When constructing code leveraging the ASP.NET 2.0 membership model that SharePoint employs, you will in due course want to hydrate a System.Web.Security.MembershipProvider object. If you have written custom membership providers, this abstract class should already be recognizable with since its members are implemented in derived provider subclasses.
Ordinarily, you hydrate a strongly typed reference to a MembershipProvider object by providing an uncomplicated index operation on the Membership.Providers collection, austerely supplying the name of the provider:
- System.Web.Security.MembershipProvider memProvider = System.Web.Security.Membership.Providers["providername"];
Not very fancy :)
An alternative is viable to this by providing two strongly typed parameters, namely a SPWebApplication and SPUrlZone, to return the strongly typed MembershipProvider. To do this, we can use a comparable approach as above, executing an index on the Membership.Providers collection. However we can automate the retrieval of the provider name using the SPWebApplication.GetIisSettingsWithFallback method consuming the SPUrlZone parameter. Subsequently, the MembershipProvider can be queried:
- public static MembershipProvider BuildMembershipProvider(SPWebApplication app, SPUrlZone zone)
- return Membership.Providers[app.GetIisSettingsWithFallback(zone).MembershipProvider];