2010-11-11 8 views
5

Comment obtenir l'élément de configuration web config?Comment obtenir l'élément de configuration web config?

ConfigurationManager.GetSection("appSettings") returns Okay 

ConfigurationManager.GetSection("location") return null 

I.E. ...

<location path="FOLDER/Page2.aspx"> 
... 
</location> 
+0

Il peut être utile si vous pouvez coller l'intégralité du contenu de votre fichier de configuration. –

Répondre

1

La raison pour laquelle vous obtenez une erreur qui est parce que dans .NET, la section de configuration d'application personnalisée (comme la section « emplacement » dans votre exemple) vous avez besoin de fournir une coutume gestionnaire de section de configuration.

L'interface principale vous devez utiliser est IConfigurationSectionHandler

Voici un article MSDN sur la façon de créer votre custom configuration handler.

5

Est-ce que cela aide?

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
ConfigurationLocationCollection myLocationCollection = config.Locations; 
foreach (ConfigurationLocation myLocation in myLocationCollection) 
{ 
    Console.WriteLine("Location Path: {0}", myLocation.Path); 
    Configuration myLocationConfiguration = myLocation.OpenConfiguration(); 
    Console.WriteLine("Location Configuration File Path: {0}",    myLocationConfiguration.FilePath); 
} 
Console.WriteLine("Done..."); 
Console.ReadLine(); 

Taken de here

+1

Cela fonctionnera pour les exécutables autonomes, c'est-à-dire la lecture depuis app.config, mais cela ne fonctionnera pas pour web.config. Dans ce cas, la première ligne doit être remplacée par 'Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration (" ~ ");' –

0

c'est parce que appSettings est une section de configuration connue (par défaut) dans une application .NET. Si vous voulez utiliser votre propre section de configuration, vous devez create it.

4

Je ne sais pas si cela est exactement ce que vous voulez, mais vous pouvez obtenir des sections dans l'élément de l'emplacement web.config comme si ...

AuthorizationSection pageAuthorizationSection = (AuthorizationSection)WebConfigurationManager.GetSection("system.web/authorizati‌​on", "FOLDER/Page2.aspx"); 
4

Je voudrais améliorer la réponse de Neil: Beaucoup disent que la modification de votre web.config à l'exécution n'est pas recommandée. Mais voici le code comment le faire.

//The path where the web.config file is located 
    string path = "~/Administrator/"; 

    //Collections of aspx page names separated by a comma. 
    //Example content in a textbox: Default.aspx,Audit.aspx, 

    string strPages = txtPages.Text; 

    //This is string array where we are going to break down all name of aspx pages 
    //contained in strPages variable 

    string[] cdrPages = strValues.Split(','); 

    //This is the list where we are going to transfer the names of our aspx pages 
    //for faster searching of existing items 

    List<string> accesslist = new List<string>(); 


    try 
     { 
      //1. Create Role 
      System.Web.Security.Roles.CreateRole(this.txtRoleName.Text); 

      //2. Open the Web Configuration --> make sure that you put the correct folder location of your web.config file 
      System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(path); 

      //3. Get All Specified Locations 
      ConfigurationLocationCollection myLocationCollection = config.Locations; 

      //4. Transfer the values of string[] strPages to List<string> accessList 
      for (int i = 0; i < strPages.Length; i++) 
      { 
       if (strPages[i].ToString() != null && strPages[i].ToString() != "") 
       { 
        accesslist.Add(strPages[i].ToString()); 
       } 
      } 

      //5. Loop through the LocationCollections 
      foreach (ConfigurationLocation myLocation in myLocationCollection) 
      { 
       //6. Checks if myLocation exists in List<string> accessList 
       bool exists = accesslist.Exists(element => element == myLocation.Path); 

       //If Exists 
       if (exists) { 

        //7. Open the configuration of myLocation 
        System.Configuration.Configuration sub = myLocation.OpenConfiguration(); 

        //8. Get the authorization section of specific location 
        AuthorizationSection section = (System.Web.Configuration.AuthorizationSection)sub.GetSection("system.web/authorization"); 

        //9. Declare the Authorization Rule, in this case, we are allowing a new role to have an access to a specific page 
        AuthorizationRule autho = new System.Web.Configuration.AuthorizationRule(System.Web.Configuration.AuthorizationRuleAction.Allow); 

        //10. Add the New Role to Authorization Section 
        autho.Roles.Add(this.txtRoleName.Text); 
        section.Rules.Add(autho); 

        //11. Save the "sub", or the specific location inside the web.config file. 
        sub.Save(); 
       } 
      } 
       message.InnerHtml = "Role Successfully Added!"; 
       message.Attributes.Add("class", "msg_info"); 
     } 
     catch { 
       message.InnerHtml = "Saving Failed"; 
       message.Attributes.Add("class", "msg_error"); 
     } 

Ceci peut être un code moche, mais c'est sûr que ça va marcher. - Jan Russel 'Rusty programmeur Calachan

Questions connexes