简体   繁体   中英

How to programmatically modify web.config in ASP.NET MVC and C# application?

This is my global.asax.cs file in my ASP.NET MVC application. I want to programmatically modify an attribute in web.config . But this error occurred:

An error occurred executing the configuration section handler for system.web/roleManager.

Code:

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)
            {

            }
        }
    }
}

The RoleManager.SectionInformation.IsLocked is true. I did try to change it to false by set:

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

but in first line this error occurred:

ConfigurationSection properties cannot be edited when locked.

The answer is: "configPath" !!!!! It should be like this:

string configPath = "~";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM