如何从 DLL 在 Winform 应用程序中使用 WCF Web 服务



>我有一个要求,我需要在类中使用服务(ASMX 或 WCF),然后我需要在 Winforms 应用程序中使用该类才能从服务获取响应。

但是问题出现了,因为 app.config 中的类(正在使用服务)的配置将被加载到 app.config 中,如果在应用程序中引用 dll,则不会读取此配置文件。

面临以下错误:

在 ServiceModel 客户端配置部分找不到引用协定"MyServices.IService"的默认终结点元素。这可能是因为找不到应用程序的配置文件,或者因为在客户端元素中找不到与此协定匹配的终结点元素。

是的,就像你所做的那样。Winform 应用程序无法识别库项目中的app.config文件。
https://learn.microsoft.com/en-us/dotnet/framework/wcf/deploying-a-wcf-library-project
此问题有两种解决方案,一种是将库项目中的配置移动到实际项目(Winform 应用程序),主要是配置中的system.servicemodel部分。 另一种是我们在代码段中对服务配置进行硬编码,我们使用通道工厂调用服务。 考虑客户端上的以下代码。

class Program
{
static void Main(string[] args)
{
BasicHttpBinding binding = new BasicHttpBinding();
Uri uri = new Uri("http://10.157.13.69:18888");
ChannelFactory<IService> factory = new ChannelFactory<IService>(binding, new EndpointAddress(uri));
IService service = factory.CreateChannel();
var result = service.GetData();
Console.WriteLine(result);
}
}
[ServiceContract]
interface IService
{
[OperationContract]
string GetData();
}

关于ChannelFactory.

https://learn.microsoft.com/en-us/dotnet/framework/wcf/samples/channel-factory https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-the-channelfactory
如果有什么我可以帮忙的,请随时告诉我。

最新更新