且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以编程方式更改端点的身份配置?

更新时间:2023-12-03 18:50:40

我认为没有办法将其内置到框架中,至少我没有发现任何简单的方法,但可能是错误的.

I don't think there is a way to do this built into the framework, at least I haven't seen anything easy but could be wrong.

我确实看到了另一个问题的答案, https://***.com/a/2068075/81251 ,它使用标准XML操作来更改端点地址.这是一个hack,但它可能会做您想要的.

I did see an answer to a different question, https://***.com/a/2068075/81251, that uses standard XML manipulation to change the endpoint address. It is a hack, but it would probably do what you want.

为完整起见,下面是链接答案中的代码:

Below is the code from the linked answer, for the sake of completeness:

using System;
using System.Xml;
using System.Configuration;
using System.Reflection;

namespace Glenlough.Generations.SupervisorII
{
    public class ConfigSettings
    {

        private static string NodePath = "//system.serviceModel//client//endpoint";
        private ConfigSettings() { }

        public static string GetEndpointAddress()
        {
            return ConfigSettings.loadConfigDocument().SelectSingleNode(NodePath).Attributes["address"].Value;
        }

        public static void SaveEndpointAddress(string endpointAddress)
        {
            // load config document for current assembly
            XmlDocument doc = loadConfigDocument();

            // retrieve appSettings node
            XmlNode node = doc.SelectSingleNode(NodePath);

            if (node == null)
                throw new InvalidOperationException("Error. Could not find endpoint node in config file.");

            try
            {
                // select the 'add' element that contains the key
                //XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
                node.Attributes["address"].Value = endpointAddress;

                doc.Save(getConfigFilePath());
            }
            catch( Exception e )
            {
                throw e;
            }
        }

        public static XmlDocument loadConfigDocument()
        {
            XmlDocument doc = null;
            try
            {
                doc = new XmlDocument();
                doc.Load(getConfigFilePath());
                return doc;
            }
            catch (System.IO.FileNotFoundException e)
            {
                throw new Exception("No configuration file found.", e);
            }
        }

        private static string getConfigFilePath()
        {
            return Assembly.GetExecutingAssembly().Location + ".config";
        }
    }
}