动态创建Webservice的datacontract

Create Webservice's datacontract dynamically

我有一个网络服务需要 return 数据。

[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; }
}

现在该服务的一些用户想要接收电话号码,其他用户不想接收该字段。

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

有没有办法根据他们是否选择接收该字段来动态做出响应?

我认为您无法在运行时更改 returning 服务中的数据,因为客户端有一批文件,包括 wsdl 作为 Web 服务的描述。此外,当网络服务被修改时,客户端需要更新网络引用。

在您的情况下,当您不知道必须 return 从服务中获取字段数时,您可以 return 字段集合。

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