【问题标题】:How to programmatically modify web.config in ASP.NET MVC and C# application?如何以编程方式修改 ASP.NET MVC 和 C# 应用程序中的 web.config?
【发布时间】:2014-12-06 08:56:03
【问题描述】:

这是我的 ASP.NET MVC 应用程序中的 global.asax.cs 文件。我想以编程方式修改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 是真的。我确实尝试通过 set 将其更改为 false:

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

但是在第一行发生了这个错误:

ConfigurationSection 属性在锁定时无法编辑。

【问题讨论】:

    标签: c# asp.net-mvc web-config


    【解决方案1】:

    答案是:“configPath”!!!!!! 应该是这样的:

    string configPath = "~";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 2018-03-22
      • 2013-12-01
      相关资源
      最近更新 更多