【问题标题】:Can't return Dictionary(Of String, String) via GET ajax web request, works with POST无法通过 GET ajax Web 请求返回 Dictionary(Of String, String),适用于 POST
【发布时间】:2010-11-05 05:17:43
【问题描述】:

我有以下网络方法:

    <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

如果我从我的 ajax 调用中使用 HttpPost,我可以很好地检索结果 (JSON),但是一旦我使用 HttpGet,我就会得到以下异常:

System.NotSupportedException:类型 System.Collections.Generic.Dictionary`2[[System.String, mscorlib , 版本=2.0.0.0, 文化=中性, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, 版本 =2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] 不受支持,因为它实现了 IDictionary

我想在这里使用 HttpGet 以便可以缓存结果。

我尝试了各种不同的调用方式,但没有运气。有任何想法吗?使用 GET 可以做到这一点吗?

【问题讨论】:

    标签: .net vb.net ajax jquery


    【解决方案1】:

    我有点困惑 - 如果 ResponseFormat 是 JSON(如上面的示例),那么 IDictionary 派生词 should be supported,但是如果它是 XML,那么我可以理解看到这个错误,因为 XmlSerializer 不支持这个。

    使用 XmlSerializer 发送字典类型的一个选项是实现将其转换为数组或 List 或 ArrayList 的逻辑。或者,您可以为数据实现自定义序列化程序并编写自己的 XML,而是从您的方法返回 XmlDocument。这将允许您以您选择的任何方式格式化数据。

    也许您可以澄清一下您使用的是 JSON 还是 XML?

    【讨论】:

    • 我使用的是 JSON,但 XML 也不起作用(除非我遗漏了什么)
    【解决方案2】:

    另一种选择是将返回类型更改为字符串,然后通过JavaScriptSerializer.Serialize 将字典转换为 JSON。这可能不是您想要返回 Dictionary 的目的,但它将是 JSON 响应中的 key=value 对。

    <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
    

    以及生成的 JSON:

    {"key1":"value1","key2":"value2"}
    

    【讨论】:

    • 这也是一个不错的选择。但是,它没有解释为什么 POST 有效而 GET 无效。
    猜你喜欢
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 2021-08-27
    • 2017-11-12
    相关资源
    最近更新 更多