2014-12-06 51 views
0

這是我的ASP.NET MVC應用程序中的global.asax.cs文件。我想以編程方式修改web.config中的屬性。但發生此錯誤:如何以編程方式修改ASP.NET MVC和C#應用程序中的web.config?

執行system.web/roleManager的配置節處理程序時發生錯誤。

代碼:

using System; 
using System.Collections.Generic; 
using System.Configuration; 
using System.Linq; 
using System.Web; 
using System.Web.Configuration; 
using System.Web.Http; 
using System.Web.Mvc; 
using System.Web.Optimization; 
using System.Web.Routing; 

namespace MyApp 
{  
    public class MvcApplication : System.Web.HttpApplication 
    { 
     protected void Application_Start() 
     { 
      AreaRegistration.RegisterAllAreas(); 
      WebApiConfig.Register(GlobalConfiguration.Configuration); 

      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
      RouteConfig.RegisterRoutes(RouteTable.Routes); 

      BundleConfig.RegisterBundles(BundleTable.Bundles); 
      AuthConfig.RegisterAuth(); 

      UsingRoleManagerSection.test(); 
     } 
    } 

    public static class UsingRoleManagerSection 
    { 
     public static void test() 
     { 
      try 
      { 
       // Set the path of the config file. 
       string configPath = "/Web.config"; 

       // Get the Web application configuration object. 
       Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath); 

       SystemWebSectionGroup web = (SystemWebSectionGroup)config.GetSectionGroup("system.web"); 


       web.ForceDeclaration(true); 
       web.RoleManager.Enabled = true; 
       web.RoleManager.SectionInformation.ForceSave = true;    
       config.Save(ConfigurationSaveMode.Modified); 
      } 
      catch (Exception ex) 
      { 

      } 
     } 
    } 
} 

RoleManager.SectionInformation.IsLocked是真實的。我曾嘗試通過設置將其更改爲false:

configSection.SectionInformation.AllowDefinition = ConfigurationAllowDefinition.Everywhere; 
configSection.SectionInformation.AllowOverride = true; 

但在第一行出現此錯誤:鎖定時

的ConfigurationSection屬性不能進行編輯。

回答

0

答案是:「configPath」!!!!! 應該是這樣的:

string configPaht = "~"; 
相關問題