c# - 当 [OperationContract] 方法中使用多个参数时,WCF 服务代理抛出异常

标签 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 设置为 wrapped 无效:

[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)] 属性吗?

关于c# - 当 [OperationContract] 方法中使用多个参数时,WCF 服务代理抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4346554/

相关文章:

c# - 从文本文件中读取,并将每一行拆分为不同的数组或列表

c# - 传递匿名类型作为方法参数

c# - 在 ASP.NET/MVC 中验证复杂情况的最佳实践?

asp.net - 如何在网站上动态显示 SVN 版本?

javascript - 通过合并数据集到 JSON 树

c# - 有没有办法将任何东西指定为 NUnit Mocks Expect 调用的参数?

asp.net - 使用密件抄送列表发送电子邮件不起作用

javascript - 在 Firefox 中注销后无法关闭选项卡

c# 如何链接 2 LinkedListNode?

linq - 在 Linq 中追加 OR 子查询