创建 WCF 绑定实例的 XML 表示 [英] Create XML representation of WCF binding instance

查看:17
本文介绍了创建 WCF 绑定实例的 XML 表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写代码以使用 WSHttpBinding.CreateBindingElements 方法.

I'm trying to write code to convert a WCF wsHttpBinding to customBinding, using the method described on WSHttpBinding.CreateBindingElements Method .

Binding wsHttpBinding = ...
BindingElementCollection beCollection = originalBinding.CreateBindingElements();
foreach (var element in beCollection)
{
    customBinding.Elements.Add(element);
}

生成自定义绑定后,我想为该新自定义绑定生成 XML 表示.(在应用程序的 .config 文件中找到的相同 XML 表示).

Once I have generated the custom binding, I want to generate an XML representation for that new custom binding. (The same XML representation that's found in an application's .config file).

有没有办法做到这一点?

Is there a way to do that?

(我知道此答案中引用的工具:https://stackoverflow.com/a/4217892/5688,但我需要可以在应用程序中调用的东西,而不依赖于云中的服务)

(I'm aware of the tool referenced in this answer: https://stackoverflow.com/a/4217892/5688, but I need something I can call within an application and without depending on a service in the cloud)

推荐答案

我正在寻找的课程是 System.ServiceModel.Description.ServiceContractGenerator

为任何类型的 Binding 的实例生成配置的示例:

Exemple to generate a configuration for an instance of any kind of Binding:

public static string SerializeBindingToXmlString(Binding binding)
{
    var tempConfig = Path.GetTempFileName();
    var tempExe = tempConfig + ".exe";
    var tempExeConfig = tempConfig + ".exe.config";
    // [... create empty .exe and empty .exe.config...]

    var configuration = ConfigurationManager.OpenExeConfiguration(tempExe);
    var contractGenerator = new ServiceContractGenerator(configuration);
    string bindingSectionName;
    string configurationName;
    contractGenerator.GenerateBinding(binding, out bindingSectionName, out configurationName);

    BindingsSection bindingsSection = BindingsSection.GetSection(contractGenerator.Configuration);

    // this needs to be called in order for GetRawXml() to return the updated config
    // (otherwise it will return an empty string)
    contractGenerator.Configuration.Save(); 

    string xmlConfig = bindingsSection.SectionInformation.GetRawXml();

    // [... delete the temporary files ...]
    return xmlConfig;
}

由于需要生成空的临时文件,这个解决方案感觉像是一个黑客,但它有效.

This solution feels like a hack because of the need to generate empty temporary files, but it works.

现在我必须寻找一种方法来拥有 System.Configuration.Configuration 的完全内存实例(可能通过编写我自己的实现)

Now I'll have to look for a way to have a fully in-memory instance of a System.Configuration.Configuration (maybe by writing my own implementation)

这篇关于创建 WCF 绑定实例的 XML 表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆