我正在尝试从另一个服务中调用 WCF 服务,部分使用我在 StackOverflow 上找到的实现ChannelFactory的示例。
我在我的测试解决方案中创建了一个单独的控制台应用程序项目(VS 2008,顺便说一句),
namespace MyService.Test
{
class Program
{
static void Main(string[] args)
{
MySolution.MyTestClient proxy = new MyTestClient();
proxy = new MyTestClient();
proxy.Endpoint.Address = new EndpointAddress("http://localhost:8723/MySolution/");
// Instantiate a request object and assign values to its member variables.
MySolution.RemoteServiceMethod() theObject = new RemoteServiceMethod();
theObject.SomeProperty = "123";
theObject.SomeOtherProperty = "alpha";
Console.WriteLine("Calling the remote service method now...");
try
{
proxy.SubmitRemoteServiceRequest(proxy.theObject);
}
catch (FaultException<MySolution.RequestException> e)
{
// exception code hereMySolution
}
}
}
}
这是来自本地服务的App.Config显示端点:
<system.serviceModel>
<client>
<endpoint address="http://MyService/MyService.asmx"
binding="basicHttpBinding" bindingConfiguration="ServiceSoap"
contract="ServiceReference.ServiceSoap"
name="ServiceSoap" />
</client>
...
</system.serviceModel>
这是来自测试项目自己的App.Config:
<client>
<endpoint address="http://localhost:8723/MyService"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IServiceContract"
contract="ServiceContract.IServiceContract" name="BasicHttpBinding_IServiceContract" />
</client>
这是我在本地服务中公开的方法,它反过来将请求对象传递给远程服务:
public ServiceContract.Response.ZZZ_Response SubmitRemoteServiceRequest(ServiceContract.Request.ZZZ_Request sc_TheirServiceRequest)
{
var factory = new ChannelFactory<ServiceReference.ServiceSoap>("ServiceSoap");
var wcfClient = factory.CreateChannel();
bool closedSuccessfully = false;
// Instantiate a response object which I will return to the consumer.
ServiceContract.Response.ZZZ_Response zzz_Response = new ServiceContract.Response.ZZZ_Response();
// Instantiate request and response objects, respectively, which I use internal to my service to call remote service.
ServiceReference.MyServiceRequest scMyServiceRequest = new ServiceReference.MyServiceRequest();
ServiceReference.MyServiceResponse scMyServiceResponse = new ServiceReference.MyServiceResponse();
try
{
// Now you can make calls on the wcfClient object
scMyServiceResponse = wcfClient.MyServiceMethod(scMyServiceRequest );
((ICommunicationObject)wcfClient).Close();
closedSuccessfully = true;
}
finally
{
if (!closedSuccessfully)
{
((ICommunicationObject)wcfClient).Abort();
}
}
return zzz_Response;
}
我收到的错误是这样的:
在 ServiceModel 客户端配置部分中找不到名为“ ServiceSoap ”和合同“ ServiceReference.ServiceSoap ”的端点元素。这可能是因为没有为您的应用程序找到配置文件,或者因为在客户端元素中找不到与此名称匹配的端点元素。
我很困惑,我到底在哪里缺少端点元素,在本地服务的 app.config(定义了指向远程服务的服务引用)、测试应用程序的 app.config 或其他地方? !
更新:阅读此 MSDN 文章后,我找到了一种解决方法,或者我猜只是实例化 ChannelFactory 的另一种方式:
var factory = new ChannelFactory<ServiceReference.ServiceSoap>(new BasicHttpBinding(), "http://urlToRemoteService/RemoteService.asmx");
我没有尝试从 app.config 中不存在或不正确的信息中获取信息,而是手动插入绑定 (BasicHttpBinding) 的值和远程服务的地址。这似乎让我摆脱了“找不到端点元素”错误,但我不确定这是否是最佳解决方案。