在方法中使用多个参数时,WCF服务代理会引发exception

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

var binding = new WebHttpBinding(); var endPoint = new EndpointAddress(string.Format(Settings.serviceBase, Settings.wcfPort)); ChannelFactory factory = new ChannelFactory(new WebHttpBinding(), endPoint); factory.Endpoint.Behaviors.Add(new WebHttpBehavior()); // **Exception occurs here** var proxy = (IzWaveSVC)factory.CreateChannel(); 

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

 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(); 

任何帮助表示赞赏。

谢谢!

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

我发现两个解决方案:

如果你可以删除

        

如果你不能,我不得不添加属性

 [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest)] 

在操作联系方法之上

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

显然,根据托管环境,存在不同的行为。

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

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

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