WebService不支持Dictionary的解决方案

2015-01-29 20:49:35|?次阅读|上传:wustguangh【已有?条评论】发表评论

关键词:C#, Web, ASP.NET|来源:唯设编程网

如果你WebService中有方法的返回值类型是Dictionary,你访问对应的.asmx页面会提示错误:不支持类型 System.Collections.Generic.Dictionary,如下所示:

WebService不支持Dictionary的解决方案

提示信息已经非常明确,WebService不支持类型Dictionary。网上查了不少资料,给出的原因是因为Dictionary不支持序列化,而WebService的数据都是通过XML进行传输,所有必须能够序列化的类型才能够被支持。

既然原因已经找到,解决问题就不难了,实现一个继承自Dictionary的泛型类MyDictionary,并实现接口IXmlSerializable,MyDictionary类的完整代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

[XmlRoot("dictionary")]
public class MyDictionary<TKey, TValue>
    : Dictionary<TKey, TValue>, IXmlSerializable
{
    /// <summary>
    /// 必须保留一个无参数的构造函数才能够序列化
    /// </summary>
    public MyDictionary():base()
    {
        
    }
    public MyDictionary(Dictionary<TKey, TValue> dictionary)
    {
        this.Clear();
        foreach (KeyValuePair<TKey, TValue> kv in dictionary)
        {
            this.Add(kv.Key, kv.Value);
        }       
    }
    #region IXmlSerializable Members
    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

        bool wasEmpty = reader.IsEmptyElement;
        reader.Read();

        if (wasEmpty)
            return;

        while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
        {
            reader.ReadStartElement("item");

            reader.ReadStartElement("key");
            TKey key = (TKey)keySerializer.Deserialize(reader);
            reader.ReadEndElement();

            reader.ReadStartElement("value");
            TValue value = (TValue)valueSerializer.Deserialize(reader);
            reader.ReadEndElement();

            this.Add(key, value);

            reader.ReadEndElement();
            reader.MoveToContent();
        }
        reader.ReadEndElement();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

        foreach (TKey key in this.Keys)
        {
            writer.WriteStartElement("item");

            writer.WriteStartElement("key");
            keySerializer.Serialize(writer, key);
            writer.WriteEndElement();

            writer.WriteStartElement("value");
            TValue value = this[key];
            valueSerializer.Serialize(writer, value);
            writer.WriteEndElement();

            writer.WriteEndElement();
        }
    }
    #endregion
}

由于MyDictionary继承自Dictionary,在WebService中将使用Dictionary的地方替换成MyDictionary,不会对你的程序造成影响。同时,MyDictionary类定义了IXmlSerializable接口的函数ReadXML和WriteXML,实现了MyDictionary对象的XML序列化,这样你的SebService就不会再报错了。

发表评论0条 】
网友评论(共?条评论)..
WebService不支持Dictionary的解决方案