如何在 MVC 和 C# 应用程序中以编程方式修改 web.config ASP.NET
本文关键字:修改 方式 编程 web config NET ASP MVC 应用程序 | 更新日期: 2023-09-27 18:33:23
这是我在 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
是真的。我确实尝试通过设置将其更改为 false:
configSection.SectionInformation.AllowDefinition = ConfigurationAllowDefinition.Everywhere;
configSection.SectionInformation.AllowOverride = true;
但是在第一行中发生了此错误:
配置节属性在锁定时无法编辑。
答案是:"configPath" !!!!它应该是这样的:
string configPath = "~";