您的位置:首页 > 其它

wcf学习笔记_2(修改wcf配置文件)

2010-05-24 19:44 483 查看
修改客户端配置文件:

在客户端的配置文件中添加<appSettings>,方便获取更改.



/// <summary>
/// 更改配置文件
/// </summary>
/// <param name="serverIp"></param>
public static void ChanageConfig(string serverIp)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
ConfigurationSectionGroup sct = config.SectionGroups["system.serviceModel"];
ServiceModelSectionGroup serviceModelSectionGroup = sct as ServiceModelSectionGroup;
ClientSection clientSection = serviceModelSectionGroup.Client;

foreach (ChannelEndpointElement item in clientSection.Endpoints)
{
string[] str = item.Address.ToString().Split('/');
string pattern ="";
for (int i = 0; i < str.Length-2; i++)
pattern += str[i] + '/';
string address = item.Address.ToString();
string replacement = string.Format("{0}", serverIp);
address = Regex.Replace(address, pattern, replacement);
item.Address = new Uri(address);
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("system.serviceModel");
}


修改服务端配置文件:

在服务端的配置文件中也添加<appSettings>,方便获取更改.





/// <summary>
/// 更改服务配置文件
/// </summary>
/// <param name="serverIp"></param>
public static void ChangeServiceConfig(string serverIp)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
ConfigurationSectionGroup sct = config.SectionGroups["system.serviceModel"];
ServiceModelSectionGroup serviceModelSectionGroup = sct as ServiceModelSectionGroup;
ServicesSection serviceSection = serviceModelSectionGroup.Services;

foreach (ServiceElement item in serviceSection.Services)
{
string address = item.Host.BaseAddresses[0].BaseAddress;
string[] str = address.Split('/');
string pattern = "";
for (int i = 0; i < str.Length - 2; i++)
pattern += str[i] + '/';
string replacement = string.Format("{0}", serverIp);
address = Regex.Replace(address, pattern, replacement);
item.Host.BaseAddresses[0].BaseAddress = address;
}
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("system.serviceModel");
}


WCF中容易出现的错误:在服务“Service1”实现的协定列表中找不到协定名称

出错的原因有两个:

1. 看契约是否写对, 这个一般不会写错

2.看配置文件:service name="空间名+服务名称" endpoint contract="空间名+契约名称"

(这里有个小细节要注意, ""中不能出现空格,否则依然报错)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐