在[OperationContract]方法中使用多个参数时,WCF服务代理会引发异常

时间:2010-12-03 14:35:23

标签: c# asp.net c#-4.0 wcf

我有一个WebServiceHost,用于在控制台应用中托管一些Web服务。我在我的客户端应用程序中添加了一个服务引用,并像这样创建代理:

var binding = new WebHttpBinding();
var endPoint = new EndpointAddress(string.Format(Settings.serviceBase, Settings.wcfPort));

ChannelFactory<IzWaveSVC> factory = new ChannelFactory<IzWaveSVC>(new WebHttpBinding(), endPoint);

factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
// **Exception occurs here**
var proxy = (IzWaveSVC)factory.CreateChannel();

它可以工作,但是一旦我添加了一个需要多个参数的新方法,我就会在创建代理时开始获取此异常(这是在任何通信发生之前):

Operation 'setDeviceState' of contract 'IzWaveSVC' specifies multiple request 
body parameters to be serialized without any wrapper elements. At most one 
body parameter can be serialized without wrapper elements. Either remove the 
extra body parameters or set the BodyStyle property on the WebGetAttribute / 
WebInvokeAttribute to Wrapped.

添加WebInvokeAttribute并将BodyStyle设置为wrap包含无效:

[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)]        
bool setDeviceState(byte nodeId, bool powered, byte level);

应该注意的是,我有其他方法可行,但它们只有一个参数,因此它们没有上述问题。

仅供参考,以下是我设置主持人的方式:

endPoint = new EndpointAddress(string.Format(Settings.serviceBase, port));
binding = new WebHttpBinding();

host = new WebServiceHost(singletonObject, new Uri(string.Format(Settings.serviceBase, port)));

host.AddServiceEndpoint(typeof(IzWaveSVC), binding, ""); 
ServiceMetadataBehavior mexBehavior = new ServiceMetadataBehavior();                
mexBehavior.HttpGetEnabled = true;
host.Description.Behaviors.Add(mexBehavior);                
host.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), endPoint.Uri.AbsoluteUri + "mex");    
host.Open();            

感谢任何帮助。

谢谢!

4 个答案:

答案 0 :(得分:15)

您似乎已使用VS中的“添加服务引用”对话框创建了代理代码。 VS ASR对话框不完全支持WCF REST,因此代理代码缺少[WebInvoke]属性。您可以尝试在客户端代理中添加[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped)]属性吗?

答案 1 :(得分:5)

我找到了两个解决方案:

如果您可以删除<webHttp/>

来自

<behaviors>
  <endpointBehaviors>
    <behavior>
      <!--<webHttp/>-->
    </behavior>
  </endpointBehaviors>
</behaviors>

如果你不能,我必须添加属性

[WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest)]

操作联系方式

答案 2 :(得分:1)

尝试在Visual Studio中更改服务的托管环境 将其从Use local IIS更改为“使用Visual Studio开发服务器”。

显然,根据托管环境,会有不同的行为。

答案 3 :(得分:0)

我有这个问题的另一种情况,即使我在操作联系方法上添加[WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest)],它仍然无法正常工作,我发现这篇文章解决了我的问题。 http://www.codemeit.com/wcf/wcf-restful-pox-json-and-soap-coexist.html

  

我们需要做的只是找到生成的文件“reference.cs”   添加服务引用后。搜索关键字:“公共接口   ITestService“在客户端项目中,您将找到生成的   服务合同,在上面添加[System.ServiceModel.Web.WebGet]   OperationContract的。

所以我在客户端代理类的OprationContract顶部添加了[System.ServiceModel.Web.WebGet],它可以工作。