将 IDictionary 对象传递给 Web 服务 [英] Passing IDictionary object to Web service

查看:27
本文介绍了将 IDictionary 对象传递给 Web 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 asmx 文件中,我有

In my asmx file, I have

        [WebMethod]
        [ScriptMethod]
        public void Method(IDictionary<string, CustomClass> objectOfCustomClass)
        {
           //do stuff
        }

自定义类定义为:

public class CustomClass
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }       
    }

一切顺利,Web 服务正在从 Jquery ajax 方法成功使用.最近我决定测试并尝试从直接 URL 访问它,例如 http://localhost/Services.asmx/Method

All goes well and the web service is being successfully consumed from Jquery ajax method. Recently I decided to test and try and access it from the direct URL such as http://localhost/Services.asmx/Method

我收到这条消息

无法序列化接口 System.Collections.Generic.IDictionary"

"Cannot serialize interface System.Collections.Generic.IDictionary"

这似乎不对.是什么原因造成的,是否正常?我很困惑 - 这似乎是一种干净的做事方式,但根据微软的说法,不应该这样做,但它有效,只是在直接访问 Web 服务时无效.是什么赋予了?我还在一些 MS 网站上读到,您不能将 IDictionary 作为参数传递给 Web 服务,但它工作正常......所以它可以完成吗?有人可以一劳永逸地澄清这一点吗?

This seems off. What's causing it and is it normal? I am confused - it seems like the clean way of doing things but according to Microsoft shouldn't be done, yet it works, only not when accessing the web service directly. What gives? I also read on some MS sites that you can't pass IDictionary to the web service as a parameter yet it works fine...SO can it be done or not? Can someone clarify this once and for all?

推荐答案

不幸的是,是的,这是正常的.您看到的是经典 ASP.NET Web 服务堆栈中 XML 序列化(XmlSerializer)的一个限制——它拒绝与任何实现 IDictionary 的东西一起工作.

Unfortunately, yes, this is normal. What you see is a limitation of XML serialization (the XmlSerializer) in the classic ASP.NET Web Service stack - it refuses to work with anything that implements IDictionary.

通过 [ScriptMethod] 暴露给 JavaScript 的服务使用不同的序列化器(JavaScriptSerializer),它没有这个限制.

The service exposed to JavaScript via [ScriptMethod] uses a different serializer (the JavaScriptSerializer), which does not have this limitation.

当您从 JavaScript 调用服务时,您会调用 JSON 端点(使用 [ScriptMethod] 声明).但是,当您从浏览器进行测试时,您会到达传统的 XML 端点(使用 [WebMethod] 声明).

When you call the service from JavaScript, you invoke the JSON endpoint (declared with [ScriptMethod]). When you test from the browser, however, you reach the traditional XML enpoint (declared with [WebMethod]).

有一些解决方法,请参见例如这个问题.但是,如果您只需要支持 AJAX 客户端,您可以简单地删除 XML 端点([WebMethod] 属性)并避免该问题.

There are some workarounds, see e.g. this question. However, if you only need to support AJAX clients, you may simply remove the XML endpoint (the [WebMethod] attribute) and avoid the issue.

顺便提一下,WCF 中改进的序列化器支持字典的序列化.

As a side note, the improved serializer in WCF supports serialization of dictionaries.

这篇关于将 IDictionary 对象传递给 Web 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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