繁体   English   中英

动态创建Webservice的数据契约

[英]Create Webservice's datacontract dynamically

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

[DataMember]
public Int32 RequestId
{
    get { return requestId; }
    set { requestId = value; }
}

[DataMember]
public string StatusCode
{
    get { return statusCode; }
    set { statusCode = value; }
}

[DataMember]
public List<string> ErrorMessages
{
    get { return errorMessages; }
    set { errorMessages = value; }
}

[DataMember]
public string PeriodStatus
{
    get { return status; }
    set { status = value; }
}
[DataMember]
public string PhoneNumber
{
    get { return status; }
    set { status = value; }
}

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

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

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

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

在您的情况下,当您不知道必须从service返回的字段数时,可以返回字段的集合。

[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方法,返回作为参数传递的特定类型的字段集合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM