Kevin Grohoske

Director of Software Development

Posted on September 7, 2007

Using Dictionary Object Params In Your Web Service

In neither .NET Framework 2.0 or 1.x can dictionary objects be used parameters for web service methods, because they are serializable.

For example the following will compile, but not work:

[WebMethod]public string MyMethod(Dictionary<string></string> CustomArguments)

You will generate the following runtime error when you test the ws:

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NotSupportedException: The type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary.

Don’t dispair I found a great option that will work!!

On Paul Welter’s Weblog

He has an example of a Serializable Dictionary Object. Copy this code into a new class, change your method signature to:

[WebMethod] public string MyMethod(SerializableDictionary<string></string> CustomArguments) { return "Success"; }

Then to use it copy or reference the class on the client side and simply do the following:

localhost.MyService wsService = new localhost.MyService(); SerializableDictionary<string></string> dict = new SerializableDictionary<string></string>(); //use it like any dictionary object dict.Add("test","me"); //call the method of the web service with the dictionary object serialized wsService.MyMethod(dict);

Note: I have noticed that when I use this method sometimes I will get compile errors that imply that I am trying to pass a DataSet rather than the SerializableDictionary object. To correct this manually go into the references.cs and change the method signatures from DataSet to SerializableDictionary. That should fix the problem.

Comments
Blog post currently doesn't have any comments.

Want to join the conversation?  Leave a comment using the form below!



 Security code