动态创建Webservice的数据契约

时间:2018-10-19 08:04:31

标签: c# web-services soap wsdl

我有一个需要返回数据的Web服务。

Hashtable h4 = new Hashtable();
Hashtable h5 = new Hashtable();

for (int i=0 ; i < 3; i++) {
    h4.put (i, "" + i);
    //System.out.println(h4.get(i));
}

for (int i=0 ; i < 3; i++) {
    h5.put (i, "++"+i);
    //System.out.println(h5.get(i));
}

Enumeration e = h4.keys();
while (e.hasMoreElements ()) {
    System.out.println(e.nextElement());
}

e = h5.keys ();
while (e.hasMoreElements()) {
    System.out.println(e.nextElement());
}

现在,该服务的某些用户希望接收电话号码,而其他用户则不想接收该字段。

这些首选项存储在数据库中。

有没有一种方法可以根据他们是否选择接收字段来动态做出响应?

1 个答案:

答案 0 :(得分:1)

我认为您不能在运行时更改从服务返回的数据,因为客户端有一批文件,其中包括wsdl作为Web服务的描述。此外,在修改Web服务后,客户端需要更新Web参考。

在您的情况下,如果您不知道必须从服务返回多少字段,则可以返回字段集合。

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[XmlInclude(typeof(CustomFieldCollection))]
[XmlInclude(typeof(CustomField))]
[XmlInclude(typeof(CustomField[]))]
public class Service : System.Web.Services.WebService
{

    public Service()
    {
    }

    [WebMethod]
    public CustomFieldCollection GetFieldsCollection()
    {
        CustomFieldCollection collection = new CustomFieldCollection();
        collection["fieldA"] = 1;
        collection["fieldB"] = true;
        collection["fieldC"] = DateTime.Now;
        collection["fieldD"] = "hello";
        CustomFieldCollection collection1 = new CustomFieldCollection();
        collection1["fieldA"] = 1;
        collection1["fieldB"] = true;
        collection1["fieldC"] = DateTime.Now;
        collection1["fieldD"] = "hello";
        collection.Collection[0].CustomFields = collection1;
        return collection;
    }
}
public class CustomFieldCollection
{
    private List<CustomField> fields = new List<CustomField>();

    public object this[String name]
    {
        get { return fields.FirstOrDefault(x => x.Name == name); }
        set
        {
            if (!fields.Exists(x => x.Name == name))
            {
                fields.Add(new CustomField(name, value));
            }
            else
            {
                this[name] = value;
            }
        }
    }

    public CustomField[] Collection
    {
        get { return fields.ToArray(); }
        set { }
    }
}


public class CustomField
{
    public string Name { get; set; }
    public object Value { get; set; }
    public CustomFieldCollection CustomFields { get; set; }

    public CustomField()
    {
    }

    public CustomField(string name, object value)
    {
        Name = name;
        Value = value;
    }
}

您可以修改GetFieldsCollection方法,返回作为参数传递的特定类型的字段的集合。