Wednesday, March 23, 2011

How do send a Collection of Enums to a WCF Service

I am having trouble sending a collection of Enums to a WCF service method. I used this post as a guide: Sharing Enum with WCF Service

[ServiceContract]
[ServiceKnownType(typeof(MyEnum))]
[ServiceKnownType(typeof(List<MyEnum>))]
public interface IMyService{    
  [OperationContract]    
  MyEnum ServiceMethod1( );

  [OperationContract]    
  IList<MyEnum> ServiceMethod2( );

  [OperationContract]    
  IList<MyEnum> ServiceMethod3( MyEnum e );

  [OperationContract]    
  IList<MyEnum> ServiceMethod4( IList<MyEnum> e );
}

[Serializable]
[DataContract]
public enum MyEnum{ 
  [EnumMember] red, 
  [EnumMember] green, 
  [EnumMember] blue 
};

ServiceMethod1, ServiceMethod2, and ServiceMethod3 work correctly. I get the following error when attempting to send a list of Enums to ServiceMethod4.

Operation 'ServiceMethod4' in contract 'IMyService' has a query variable named 'e' of type 'System.Collections.Generic.IList`1[MyEnum]', but type 'System.Collections.Generic.IList`1[MyEnum]' is not convertible by 'QueryStringConverter'.  Variables for UriTemplate query values must have types that can be converted by 'QueryStringConverter'.

Do I need to create a custom QueryStringConverter?

Thanks!

From stackoverflow
  • What does your configuration file look like? It sounds like you might be using a webHttpBinding element which would not support IList<MyEnum> as that would be impossible to represent on a URL.

    You should look into using a basicHttpBinding as this uses SOAP. Using SOAP will allow you to serialize IList<MyEnum> and send it to your OperationContract.

    Corey Coto : I am using a `webHttpBinding` element and calling my service with a simple Get request passing the params on the query string. http://server/MyService.svc/ServiceMethod4?e=0&e=1&e=2 Why doesn't `webHttpBinding` serialize a list of enums? `webHttpBinding` will serialize a list of objects.
  • Would it be acceptable to type that parameter as an array of MyEnum instead? Then inside your implementation just use var eList = new List(e); Alternatively, you could try using a KnownType helper class, as outlined here: http://msdn.microsoft.com/en-us/library/system.servicemodel.serviceknowntypeattribute.aspx

    Corey Coto : I previously tried changing the type of the parameter to an array of MyEnums but the parameter still doesn't serialize. I am also using the ServiceKnownType attribute as shown in the example above but it doesn't help the situation either.

0 comments:

Post a Comment