Accessing Membership Details in web.config Programmatically

The default membership provider from the machine.config file looks like this (except I substituted myApp in for / as the applicationName):

<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

I wanted to read the applicationName attribute into a variable in one of my code-behind files. My first attempt at this worked, but was not so good. The code:

 // using the System.Configuration and System.Xml namespaces

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
MembershipSection mem = config.GetSection("system.web/membership") as MembershipSection;
SectionInformation sectionInfo = mem.SectionInformation;
XmlDocument memdoc = new XmlDocument();
XmlElement el = memdoc.GetElementsByTagName("add")[0] as XmlElement;
XmlAttribute appNameAttrib = el.Attributes["applicationName"];
appName.Text = appNameAttrib.Value;

The MSDN documentation on the GetRawXml method of the SectionInformation class states that: “This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.”
I immediately concluded that I had not gone about this the correct way; the .NET way. So, I revisited the MembershipSection class to see if I’d missed something. And sure enough, it leapt out at me…the Providers property! The revised code is:

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
MembershipSection memSection = config.GetSection("system.web/membership") as MembershipSection;
ProviderSettingsCollection membershipProviders = memSection.Providers;
ProviderSettings memSettings = membershipProviders["AspNetSqlMembershipProvider"];
appName.Text = memSettings.Parameters["applicationName"];

The Parameters collection has the NameValueCollection type, the values of which are accessible by keys. So, the key “applicationName” returns the value ascribed to that key i.e. “myApp”.

The other thing I noted was the performance increase. It’s much faster doing things the way they were intended!

  1. Looks good, it is definitely a better way to deal with config. it is faster because the second approach has the automatic caching built-in; also deserialization is better as well.

    But for what you were trying to archive (get ApplicationName), I guess the following code might just work (I haven’t tried):

    string applicationName = Membership.Provider.ApplicationName;



  2. Steve, you are totally right! Awesome. Your way is so much cleaner as well. Big cheers!!!

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>