我有一个需要返回数据的网络服务。
[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引用。
在您的情况下,当您不知道必须从服务返回的字段数时,您可以返回字段集合。
[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 方法,返回作为参数传递的特定类型的字段集合。