0

I have the following web method:

    <WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True, XmlSerializeString:=True)> _
    Public Function GetDictionary() As Dictionary(Of String, String)

        Dim d As New Dictionary(Of String, String)
        d.Add("key1", "value1")
        d.Add("key2", "value2")
        Return d

    End Function

I can retrieve the results fine (JSON) if I use HttpPost from my ajax call, but as soon as I use HttpGet I get the following exception:

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

I wanted to use HttpGet here so that the result can be cached.

I tried every variation of calling this, but no luck. Any ideas? Is this possible with GET?

ScottE
  • 21,530
  • 18
  • 94
  • 131
  • For anyone coming here recently I believe you need to set the `Content-Type:` request header to `application/json`. – Matt May 31 '23 at 22:16

2 Answers2

1

I'm a little confused - if the ResponseFormat is JSON (as in your example above) then IDictionary derivatives should be supported, however if it is XML then I could understand seeing this error as the XmlSerializer does not support this.

One option to send a dictionary type using the XmlSerializer is to implement logic to convert it to an array or List or ArrayList. Alternatively you could implement a custom serializer for the data and write your own XML, returning an XmlDocument from your method instead. This would allow you to format the data in any way you choose.

Maybe you could clarify if you are using JSON or XML?

Jon Grant
  • 11,369
  • 2
  • 37
  • 58
1

Another alternative is to change the Return type to a String and then convert the Dictionary to JSON via JavaScriptSerializer.Serialize. This may not be exactly what you were intending with returning a Dictionary but it will be key=value pairs in the JSON Response.

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True, XmlSerializeString:=True)> _
Public Function GetDictionary() As String

    Dim d As New Dictionary(Of String, String)
    d.Add("key1", "value1")
    d.Add("key2", "value2")
    Return New JavaScriptSerializer().Serialize(d)

End Function

And the resulting JSON:

{"key1":"value1","key2":"value2"}
Rick Hochstetler
  • 3,043
  • 2
  • 20
  • 16