简体   繁体   English

如何以编程方式修改 ASP.NET MVC 和 C# 应用程序中的 web.config?

[英]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.这是我的 ASP.NET MVC 应用程序中的global.asax.cs文件。 I want to programmatically modify an attribute in web.config .我想以编程方式修改web.config的属性。 But this error occurred:但是出现了这个错误:

An error occurred executing the configuration section handler for system.web/roleManager.执行 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. RoleManager.SectionInformation.IsLocked为真。 I did try to change it to false by set:我确实尝试通过设置将其更改为 false:

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

but in first line this error occurred:但在第一行发生了这个错误:

ConfigurationSection properties cannot be edited when locked.锁定时无法编辑 ConfigurationSection 属性。

The answer is: "configPath" !!!!!答案是:“configPath”!!!!! It should be like this:应该是这样的:

string configPath = "~";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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