开发者

calling asmx from server side

I wrote an asmx service on one server1 and and asp.net/c# on another server2.

I w开发者_开发问答ant to transfer a dictionary<string,string> from srv1 to srv2. I read Dictionary is not serializable and should be sent as List<KeyValuePair<string,string>>.

on srv2 I try to read the result but it's of type:

KeyValuePairOfStringString[] result = response.GetTemplatesParamsPerCtidResult;

i try to retrieve the key,value but cannot unflat each element:

 foreach (var pair in result)
   {
// pair has just 4 generic methods: toString, GetHashCode,GetType,Equals
   }

How do I do this? Is there anything I should change in my implementation?

TIA


How about using an array MyModel[] where MyModel looks like this:

public class MyModel
{
    public string Key { get; set; }
    public string Value { get; set; }
}

Generics should be avoiding when exposing SOAP web services.


XmlSerializer won't serialize objects that implement IDictionary by default.

One way around this is to write a new class that wraps an IDictionary object and copies the values into an array of serializable objects.

So you can write a class like that :

public class DictionarySerializer : IXmlSerializable
{
    const string NS = "http://www.develop.com/xml/serialization";

    public IDictionary dictionary;

    public DictionarySerializer() 
    {
        dictionary = new Hashtable();
    }
    public DictionarySerializer(IDictionary dictionary)
    {
        this.dictionary = dictionary;
    }

    public void WriteXml(XmlWriter w)
    {
        w.WriteStartElement("dictionary", NS);
        foreach (object key in dictionary.Keys)
        {
            object value = dictionary[key];
            w.WriteStartElement("item", NS);
            w.WriteElementString("key", NS, key.ToString());
            w.WriteElementString("value", NS, value.ToString());
            w.WriteEndElement();
        }
        w.WriteEndElement();
    }

    public void ReadXml(XmlReader r)
    {
        r.Read(); // move past container
        r.ReadStartElement("dictionary");
        while (r.NodeType != XmlNodeType.EndElement)
        {            
            r.ReadStartElement("item", NS);
            string key = r.ReadElementString("key", NS);
            string value = r.ReadElementString("value", NS);
            r.ReadEndElement();
            r.MoveToContent();
            dictionary.Add(key, value);
        }
    }
    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return LoadSchema();
    }
}

You then create your webservice method with this return type.

[WebMethod]
public DictionarySerializer GetHashTable()
{
    Hashtable ht = new Hashtable();
    ht.Add(1, "Aaron");
    ht.Add(2, "Monica");
    ht.Add(3, "Michelle");
    return new DictionarySerializer (h1);
}

If you need more information, the paper contain some information about this technic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜