无法从WCF服务返回数组 [英] Cannot return array from WCF service

查看:91
本文介绍了无法从WCF服务返回数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从WCF服务返回数组。在我的服务中分配的任何值都不会返回给客户。



这是我的服务界面:



I cannot return an array from a WCF service. Any values assigned in my service are not returned to the client.

Here is my service interface:

[ServiceContract]
public interface IMyService
{
   [OperationContract]
   void ReturnArray(byte[] a);

   [OperationContract]
   byte[] ReturnArrayEx(byte[] a);
}





这是我的具体服务类:





Here is my concrete service class:

[KnownType(typeof(byte[]))]
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
public class MyService : IMyService
{
   public void ReturnArray(byte[] a)
   {
      a[0] = 11;
      a[1] = 21;
   }

   public byte[] ReturnArrayEx(byte[] a)
   {
      byte[] temp = a;

      a[0] = 33;
      a[1] = 44;

      return a;
   }
}





我通过以下代码自行托管我的服务:





I am self-hosting my service with the following code:

string address;
ChannelFactory<ChannelTest.IMyService> channelFactory;

BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Mode = BasicHttpSecurityMode.None; // None is the default

address = @"http://localhost:12345/MyService";
channelFactory = new ChannelFactory<ChannelTest.IMyService>(binding, address);
m_service = channelFactory.CreateChannel();





我按如下方式调用我的服务:





I invoke my service as follows:

byte[] myArray = new byte[5];
m_service.ReturnArray(myArray);





返回时,我的数组仍然包含默认的零而不是11和21分配的在服务中。



一篇文章建议第二种方法(ReturnArrayEx)是返回数组的方法,但必须有更好的方法。



我需要分配更多KnownTypes吗?我必须设置其他属性吗?有没有我需要改变的设置?



On return, my array still contains its default zeroes rather than 11 and 21 assigned in the service.

An article suggested that the second method (ReturnArrayEx) is the way to return arrays, but there has to be a better way.

Do I need to assign more KnownTypes? Are there other attributes I must set? Is there a setting somewhwere I need to change?

推荐答案

第一个问题,没有阅读你的其余问题:方法 ReturnArray 不返回任何数组。它只是修改了一些现有数组的两个第一个元素,并且只有在初始化此数组时才有至少两个元素,否则赋值操作会抛出异常。彻底摆脱这种方法;这没有任何意义,不是因为它的实现,而是因为它的特色。



-SA
First problem, without reading the rest of your question: the method ReturnArray does not return any arrays. It simply modifies two first elements of some existing array, and only if this array was initialized to have at least two elements, otherwise the assignment operation throws exception. Get rid of this method completely; it makes no sense, not because of its implementation, but due to its very signature.

—SA

解决方案很简单。方法签名应如下:



The solution was simple. The method signature should be as follows:

void ReturnArray(ref byte[] a);







注意'ref'已被添加。




Note that 'ref' was added.


这篇关于无法从WCF服务返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆