Daily Archives: 3 July 2009

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=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LocalSqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="myApp"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression="">

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();
memdoc.LoadXml(sectionInfo.GetRawXml());
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!