【发布时间】:2018-12-31 16:56:11
【问题描述】:
考虑一下微软的例子:https://docs.microsoft.com/en-us/dotnet/framework/wcf/how-to-create-a-wcf-client
如何使用简单的 HttpClient 对象来使用服务器?
在某些情况下,无法向您的项目添加 Web 引用。然后,使用 HttpClient 对象可能是唯一的方法......或者向客户端添加服务器 DLL 引用也可能是一种选择。
这应该是一个简单的例子,说明如何调用下面描述的简单 double = Add(double, double) 函数:
namespace GettingStartedLib
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
}
}
服务器端如下:
namespace GettingStartedLib
{
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
double result = n1 + n2;
Console.WriteLine("Received Add({0},{1})", n1, n2);
// Code added to write output to the console window.
Console.WriteLine("Return: {0}", result);
return result;
}
}
}
【问题讨论】:
-
“使用简单的 HttpClient 对象来消费服务器”但是为什么呢?它破坏了 WCF 的全部目的! WCF 是关于创建代理类和执行远程功能,就好像它们是本地的一样。它非常简单和有用。现在你只想忽略所有这些并使用一些疯狂的东西......为什么?如果您想使用 HttpClient 使用它,只需创建一个 API 项目。
标签: wcf httpclient