从Windows应用程序访问WCF服务方法

时间:2015-07-29 14:15:54

标签: c# asp.net wcf windows-applications

我有一个WCf服务,它有这个默认方法

public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

在Windows应用程序中,我已将此方法作为

访问
private async void btnLogin_Click_1(object sender, RoutedEventArgs e)
        {
            ServiceReference1.Service1Client client = new   ServiceReference1.Service1Client();
            var res = await client.GetDataAsync(78);
            txtUsername.Text = res;
}

正如你在我的方法中看到的,我正在返回一个字符串值。但是当我试图在文本框中显示它时,它会给出错误

  

无法隐式转换类型   ' ApplicationName.ServiceReference1.GetDataResponse'到'字符串'

如果我使用res.ToString(),则会打印

  

ClaimAssistantApplication.ServiceReference1.GetDataResponse

这不是我的方法返回的字符串。我是WCF服务的新手。是否有任何方法来访问输出字符串?

1 个答案:

答案 0 :(得分:1)

您对此应如何工作的期望是不正确的。

如果您想了解原因,请查看您的服务WSDL。您可以使用visual studio命令提示符中的disco.exe工具执行此操作,该工具将所有服务元数据下载到目录:

<script id="innerTemplate" type="text/ng-template">
  Hello world
</script>


<script id="outerTemplate" type="text/ng-template">
  My name is John!
  <p ng-include="'innerTemplate'"></p>
</script>

<div ng-include="'outerTemplate'"></div>

在您的服务WSDL中,您将看到其中有一个disco /out:myOutputDir http://MyServiceAddress 元素,用于定义您的服务操作。类似的东西:

wsdl:operation

如果查看该元素,您应该看到定义了<wsdl:operation name="GetData"> 消息类型。按惯例,这将被称为:

wsdl:output

因此,在您的实例中,消息将被定义为GetDataResponse类型。这是您使用和调用服务元数据定义的服务操作时返回的实际类型。

实际上,如果您使用fiddler或类似的东西来调用服务操作,您应该会看到返回的实际响应消息。它看起来像这样:

(operation name)Response

您应该能够在您下载的服务元数据中找到<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <SOAP-ENV:Body> <m:GetDataResponse xmlns:m="YourServiceNamespace"> <getData>You entered: 78</getData> </m:GetDataResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope> 类型,无论是内联还是其中一个.xsd文件。

因此,当您向服务添加服务引用时,正在发生的事情是Visual Studio下载服务元数据,读取它,然后生成允许您调用服务的C#代码。在生成该服务操作时,visual studio发现GetDataResponse XSD类型是GetData服务操作的返回类型,因此它生成一个名为GetDataResponse的C#类型,并将其指定为Service1Client.GetData和GetDataAsync的返回类型。方法

如果您希望检索操作响应的实际字符串值,则需要深入研究GetDataResponse类型(我相信它将被称为“值”,但我不记得了。)

希望这有助于您理解。

相关问题