.net用代码配置Web.config文件

简介: public class Webconfig     {         private string XmlFilePath;         private XmlDocument xmldoc;         #region 构造...

public class Webconfig
    {
        private string XmlFilePath;
        private XmlDocument xmldoc;

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="FilePath">配置文件的路径</param>
        public Webconfig(string FilePath)
        {
            XmlFilePath = FilePath;
            xmldoc = new XmlDocument();//新xml文档对象
            if (File.Exists(XmlFilePath)) xmldoc.Load(XmlFilePath);  //如果文件存在,则加载现有的xml文档
        }
        #endregion

        #region 设置和获得AppSettings的值
        /// <summary>
        /// 获得AppSetting的值
        /// </summary>
        /// <param name="KeyName">节点名(key的值)</param>
        /// <returns></returns>
        public string AppSetting_Get(string KeyName)
        {
            XmlNodeList list = xmldoc.SelectNodes("/configuration/appSettings/add");
            foreach (XmlNode node in list)
            {
                XmlElement xe = (XmlElement)node;
                if (xe.GetAttribute("key") == KeyName) return xe.GetAttribute("value");
            }
            return "";

        }

        /// <summary>
        /// appSettings下的配置字符串
        /// </summary>
        /// <param name="KeyName">key的值</param>
        /// <param name="ValueString">value的值</param>
        public void AppSetting_Set(string KeyName, string ValueString)
        {
            InitNode("/configuration/appSettings");
            XmlNodeList list = xmldoc.SelectNodes("/configuration/appSettings/add");
            if (ValueString == "")
            {
                ValueString = "Data Source=.;Initial Catalog=数据库名;uid=用户名;pwd=密码";
            }
            bool isexist = false;
            foreach (XmlNode node in list)
            {
                XmlElement xe = (XmlElement)node;
                if (xe.GetAttribute("key") == KeyName)
                {
                    xe.SetAttribute("value", ValueString);
                    isexist = true;
                }
            }
            if (!isexist)
            {
                XmlElement xe1 = xmldoc.CreateElement("add");
                xe1.SetAttribute("key", KeyName);
                xe1.SetAttribute("value", ValueString);
                xmldoc.SelectSingleNode("/configuration/appSettings").AppendChild(xe1);
            }
            xmldoc.Save(XmlFilePath);

        }

        #endregion

        #region httpModules下的配置字符串

        public void httpModules_Set()
        {
            InitNode("/configuration/system.web/httpModules");
            XmlNodeList list = xmldoc.SelectNodes("/configuration/system.web/httpModules/add");
            bool isexist = false;
            foreach (XmlNode node in list)
            {
                XmlElement xe = (XmlElement)node;
                if (xe.GetAttribute("name") == "MyModule")
                {
                    xe.SetAttribute("type", "Tools.Mymodule,Tools");
                    isexist = true;
                }

            }
            if (!isexist)
            {
                XmlElement xe1 = xmldoc.CreateElement("add");
                xe1.SetAttribute("name", "MyModule");
                xe1.SetAttribute("type", "Tools.Mymodule,Tools");
                xmldoc.SelectSingleNode("/configuration/system.web/httpModules").AppendChild(xe1);
            }
            xmldoc.Save(XmlFilePath);

        }
        #endregion

        #region 设置sessionState的字符串

        public void SessionState_Set()
        {
            InitNode("/configuration/system.web/sessionState");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/system.web/sessionState");
            xe.SetAttribute("mode", "StateServer");
            xe.SetAttribute("stateConnectionString", "tcpip=localhost:42424");
            xe.SetAttribute("sqlConnectionString", "data source=127.0.0.1;Trusted_Connection=yes");
            xe.SetAttribute("cookieless", "false");
            xe.SetAttribute("timeout", "40");
            xmldoc.Save(XmlFilePath);
        }
        #endregion

        #region 设置httpRuntime的字符串

        public void httpRuntime_Set()
        {
            InitNode("/configuration/system.web/httpRuntime");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/system.web/httpRuntime");
            xe.SetAttribute("maxRequestLength", "2048000");
            xe.SetAttribute("executionTimeout", "900");
            xe.SetAttribute("useFullyQualifiedRedirectUrl", "true");
            xe.SetAttribute("appRequestQueueLimit", "150");
            xe.SetAttribute("minFreeThreads", "18");
            xe.SetAttribute("minLocalRequestFreeThreads", "15");
            xmldoc.Save(XmlFilePath);
        }
        #endregion

        #region 设置customErrors的字符串

        public void customErrors_Set()
        {
            InitNode("/configuration/system.web/customErrors");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/system.web/customErrors");
            xe.SetAttribute("mode", "RemoteOnly");
            xe.SetAttribute("redirectMode", "ResponseRewrite");
            xe.SetAttribute("defaultRedirect", "~/一般错误提示.aspx");
            XmlNodeList list = xe.ChildNodes;
            bool[] isexist = { false, false };
            foreach (XmlNode node in list)
            {
                XmlElement element = (XmlElement)node;
                if (element.GetAttribute("statusCode") == "403")
                {
                    element.SetAttribute("redirect", "~/无权限时的提示页面.aspx");
                }
                else if (element.GetAttribute("statusCode") == "403")
                {
                }
            }
            XmlElement xe1 = null;
            if (isNodeExist(list, "statusCode", "403", ref xe1))
            {
                xe1.SetAttribute("redirect", "~/无权限时的提示页面.aspx");
            }
            else
            {
                xe1 = xmldoc.CreateElement("error");
                xe1.SetAttribute("statusCode", "403");
                xe1.SetAttribute("redirect", "~/无权限时的提示页面.aspx");
                xe.AppendChild(xe1);
            }

            XmlElement xe2 = null;
            if (isNodeExist(list, "statusCode", "404", ref xe2))
            {
                xe2.SetAttribute("redirect", "~/找不到时的提示页面.aspx");
            }
            else
            {
                xe2 = xmldoc.CreateElement("error");
                xe2.SetAttribute("statusCode", "404");
                xe2.SetAttribute("redirect", "~/找不到时的提示页面.aspx");
                xe.AppendChild(xe2);
            }
            xmldoc.Save(XmlFilePath);
        }

        #endregion

        #region 查询是否存在结点 isNodeExist
        /// <summary>
        /// 查询是否存在结点 isNodeExist
        /// </summary>
        /// <param name="list">节点列表</param>
        /// <param name="AttrKey">属性键名</param>
        /// <param name="AttrValue">属性值</param>
        /// <param name="Element">引用的XmlElement值</param>
        /// <returns></returns>
        public bool isNodeExist(XmlNodeList list, string AttrKey, string AttrValue, ref XmlElement Element)
        {
            bool isExist = false;
            foreach (XmlNode node in list)
            {
                XmlElement xe = (XmlElement)node;
                if (xe.GetAttribute(AttrKey) == AttrValue)
                {
                    isExist = true;
                    Element = xe;
                    break;
                }
            }
            return isExist;
        }
        #endregion

        #region 设置configSections下的log4net的字符串

        public void configSections_Set_log4net()
        {
            InitNode("/configuration/configSections");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/configSections");
            XmlNodeList list = xmldoc.SelectNodes("/configuration/configSections/section");
            XmlElement Log4Net=null;
            if (isNodeExist(list, "name", "log4net", ref Log4Net))
            {
                Log4Net.SetAttribute("type", "log4net.Config.Log4NetConfigurationSectionHandler, log4net");
            }
            else
            {
                Log4Net = xmldoc.CreateElement("section");
                Log4Net.SetAttribute("name","log4net");
                Log4Net.SetAttribute("type", "log4net.Config.Log4NetConfigurationSectionHandler, log4net");
                xe.InsertBefore(Log4Net,xe.FirstChild);//在xe节点下插入子节点,插在最前
            }
            xmldoc.Save(XmlFilePath);
        }

        #endregion

        #region 设置log4net的字符串

        public void log4net_Set()
        {
            XmlComment xc;
            InitNode("/configuration/log4net");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/log4net");
           
            xc = xmldoc.CreateComment("在 Global类中Application_Start函数中加入 log4net.Config.XmlConfigurator.Configure();");
            xe.AppendChild(xc);
            xc = xmldoc.CreateComment("用之前得到对象: private ILog logger = LogManager.GetLogger(typeof(类名));");
            xe.AppendChild(xc);

            XmlElement xe2;
            string logNodePath = "/configuration/log4net/appender";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("name","RollingLogFileAppender");
            xe2.SetAttribute("type", "log4net.Appender.RollingFileAppender");

            logNodePath = "/configuration/log4net/appender/file";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "Log4net.log");

            logNodePath = "/configuration/log4net/appender/appendToFile";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "true");

            logNodePath = "/configuration/log4net/appender/maxSizeRollBackups";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "10");

            logNodePath = "/configuration/log4net/appender/maximumFileSize";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "1024KB");

            logNodePath = "/configuration/log4net/appender/rollingStyle";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "Size");

            logNodePath = "/configuration/log4net/appender/staticLogFileName";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "true");

            logNodePath = "/configuration/log4net/appender/layout";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("type", "log4net.Layout.PatternLayout");

            logNodePath = "/configuration/log4net/appender/layout/conversionPattern";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value", "%date [%thread] %-5level %logger - %message%newline");

            InitNode("/configuration/log4net/root");

            logNodePath = "/configuration/log4net/root/level";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("value","DEBUG");

            logNodePath = "/configuration/log4net/root/appender-ref";
            InitNode(logNodePath);
            xe2 = (XmlElement)xmldoc.SelectSingleNode(logNodePath);
            xe2.SetAttribute("ref", "RollingLogFileAppender");
            xmldoc.Save(XmlFilePath);
        }

        #endregion

        #region 设置system.web下的identity的字符串

        public void identity_Set()
        {
            InitNode("/configuration/system.web/identity");
            XmlElement xe = (XmlElement)xmldoc.SelectSingleNode("/configuration/system.web/identity");
            xe.SetAttribute("impersonate", "true");
            xmldoc.Save(XmlFilePath);
        }

        #endregion

        #region 初始化全部路径
        /// <summary>
        /// 初始化全部路径
        /// </summary>
        /// <param name="FilePath">内部为Xml格式的文件路径</param>
        /// <param name="NodePath">相对于根的节点路径</param>
        /// <returns>提示信息,ok为成功</returns>
        public string InitNode(string NodePath)
        {
            string Result = "ok";

            string[] nodes = NodePath.Trim('/').Split('/');
            XmlNode node = xmldoc.SelectSingleNode(NodePath.TrimEnd('/'));
            if (node == null) //如果不存在,则要创建和保存
            {
                XmlNode nodeParent;
                XmlNode nodeTemp;
                XmlElement ElementNew;
                string tempPath = "";//当前节点路径
                string parentPath = "";//父节点路径
                for (int i = 0; i < nodes.Length; i++)
                {
                    tempPath += "/" + nodes[i];
                    nodeTemp = xmldoc.SelectSingleNode(tempPath);
                    if (nodeTemp == null)
                    {
                        ElementNew = xmldoc.CreateElement(nodes[i]);
                        if (parentPath == "")
                        {
                            if (xmldoc.HasChildNodes)
                            {
                                Result = "此文档已有根结点,不能再创建一个根结点!";
                                return Result;
                            }
                            else xmldoc.AppendChild(ElementNew);
                        }
                        else
                        {
                            nodeParent = xmldoc.SelectSingleNode(parentPath);
                            nodeParent.AppendChild(ElementNew);
                        }
                    }
                    parentPath = tempPath;

                }
                xmldoc.Save(XmlFilePath);
            }
            return Result;
        }
        #endregion

    }

 

相关文章
|
1月前
|
开发框架 前端开发 JavaScript
ASP.NET Web Pages - 教程
ASP.NET Web Pages 是一种用于创建动态网页的开发模式,采用HTML、CSS、JavaScript 和服务器脚本。本教程聚焦于Web Pages,介绍如何使用Razor语法结合服务器端代码与前端技术,以及利用WebMatrix工具进行开发。适合初学者入门ASP.NET。
|
3月前
|
Java API 数据库
构建RESTful API已经成为现代Web开发的标准做法之一。Spring Boot框架因其简洁的配置、快速的启动特性及丰富的功能集而备受开发者青睐。
【10月更文挑战第11天】本文介绍如何使用Spring Boot构建在线图书管理系统的RESTful API。通过创建Spring Boot项目,定义`Book`实体类、`BookRepository`接口和`BookService`服务类,最后实现`BookController`控制器来处理HTTP请求,展示了从基础环境搭建到API测试的完整过程。
66 4
|
8天前
|
开发框架 数据可视化 .NET
.NET 中管理 Web API 文档的两种方式
.NET 中管理 Web API 文档的两种方式
30 14
|
24天前
|
运维 前端开发 C#
一套以用户体验出发的.NET8 Web开源框架
一套以用户体验出发的.NET8 Web开源框架
一套以用户体验出发的.NET8 Web开源框架
|
26天前
|
算法 Java 测试技术
使用 BenchmarkDotNet 对 .NET 代码进行性能基准测试
使用 BenchmarkDotNet 对 .NET 代码进行性能基准测试
57 13
|
1月前
|
开发框架 .NET PHP
ASP.NET Web Pages - 添加 Razor 代码
ASP.NET Web Pages 使用 Razor 标记添加服务器端代码,支持 C# 和 Visual Basic。Razor 语法简洁易学,类似于 ASP 和 PHP。例如,在网页中加入 `@DateTime.Now` 可以实时显示当前时间。
|
2月前
|
JavaScript 前端开发 开发工具
web项目规范配置(husky、eslint、lint-staged、commit)
通过上述配置,可以确保在Web项目开发过程中自动进行代码质量检查和规范化提交。Husky、ESLint、lint-staged和Commitlint共同作用,使得每次提交代码之前都会自动检查代码风格和语法问题,防止不符合规范的代码进入代码库。这不仅提高了代码质量,还保证了团队协作中的一致性。希望这些配置指南能帮助你建立高效的开发流程。
89 5
|
3月前
|
安全 Java 网络安全
Android远程连接和登录FTPS服务代码(commons.net库)
Android远程连接和登录FTPS服务代码(commons.net库)
49 1
|
3月前
|
JavaScript 前端开发 应用服务中间件
vue前端开发中,通过vue.config.js配置和nginx配置,实现多个入口文件的实现方法
vue前端开发中,通过vue.config.js配置和nginx配置,实现多个入口文件的实现方法
247 0
|
3月前
|
XML JSON API
ServiceStack:不仅仅是一个高性能Web API和微服务框架,更是一站式解决方案——深入解析其多协议支持及简便开发流程,带您体验前所未有的.NET开发效率革命
【10月更文挑战第9天】ServiceStack 是一个高性能的 Web API 和微服务框架,支持 JSON、XML、CSV 等多种数据格式。它简化了 .NET 应用的开发流程,提供了直观的 RESTful 服务构建方式。ServiceStack 支持高并发请求和复杂业务逻辑,安装简单,通过 NuGet 包管理器即可快速集成。示例代码展示了如何创建一个返回当前日期的简单服务,包括定义请求和响应 DTO、实现服务逻辑、配置路由和宿主。ServiceStack 还支持 WebSocket、SignalR 等实时通信协议,具备自动验证、自动过滤器等丰富功能,适合快速搭建高性能、可扩展的服务端应用。
216 3