asp.netweb-configconfiguration-fileswebconfigurationmanager

Trying to open a section from the web.config spans a ConfigurationErrorsException: The entry KEY has already been added


I'm trying to fetch some settings from my membership provider in my asp.net application (so that I don't have to duplicate the information in the appSettings section) but I am getting the following exception:

System.Configuration.ConfigurationErrorsException: The entry 'MyMembershipProvider' has already been added. (C:\Inetpub\intranet-webapp\web.config line 53)

My code is the following:

var configurationManager = WebConfigurationManager.OpenWebConfiguration("/", "IntranetWebapp");
var section = (MembershipSection) configurationManager.GetSection("system.web/membership");

The exception is raised in the second line. I find it completely bizarre, since I am not trying to add any new information to the config file. Instead I'm just trying to retrieve it.

The contents of my config section:

<membership defaultProvider="IntranetApp">
  <providers>
    <add applicationName="IntranetApp"
         enableSearchMethods="true"
         connectionStringName="IntranetConnectionString"
         connectionUsername="CN=username,OU=Service Accounts,OU=Users,OU=CompanyName,DC=CompanyName,DC=com"
         connectionPassword="********"
         name="MyIntranetMembershipProvider"
         type="System.Web.Security.ActiveDirectoryMembershipProvider" />
  </providers>
</membership>

Any help is much appreciated.

Pablo


Solution

  • Assuming the fix from my comment, I can't see anything wrong with your code - using the exact same thing (with a different value for the site property obviously) results in a populated section variable as I'd expect.

    The only thing I can think of is that you're either doing something else with ConfigurationFile.Getsection, that is attempting to merge the data into your main setting, or by using the overload of OpenWebConfiguration that takes a site you've managed to open a web.config from a different area in the hierarchy into your site - do you have either multiple applications defined in IIS/.NET that would have conflicting values for their Membership setting?

    Finally, shouldn't you DefaultProvider value read "MyIntranetMembershipProvider", which is the name of your provider, rather than "IntranetApp" which is the name of the application (in the provider's datastore).