WCF服务的默认值 [英] WCF Service default values
问题描述
我有以下的数据合同类为我的WCF服务:
I have following data contract class for my WCF Service:
[DataContract(Name = "MyClassDTO")]
public class MyClass
{
private string name = "Default Name";
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
当我使用Visual Studio的添加服务引用函数生成一个WCF服务引用生成的DataContract看起来是这样的:
When I use Visual Studio's Add Service Reference function to generate a WCF Service Reference the generated DataContract looks something like this:
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name = "MyClassDTO", Namespace = "xxx")]
[System.SerializableAttribute()]
public partial class MyClassDTO : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged
{
[System.Runtime.Serialization.OptionalFieldAttribute()]
private string NameField;
[System.Runtime.Serialization.DataMemberAttribute()]
public string Name
{
get
{
return this.NameField;
}
set
{
if ((object.ReferenceEquals(this.NameField, value) != true))
{
this.NameField = value;
this.RaisePropertyChanged("Name");
}
}
}
}
这意味着,默认值为默认名称丢失和出现以下行为:
That means, the default value "Default Name" gets lost and following behavior occurs:
MyClassDTO mcdto = new MyClassDTO();
serviceClient.DoSomething(mcdto);
[OperationContract]
void DoSomething(MyClass mc){
mc.Name //<-- == null but I want it to be "Default Name"
}
有没有办法配置数据契约的方式,该定义的默认值默认名称不迷路?
Is there a way configure the data contract that way, that the defined default value "Default Name" doesn't get lost?
其他信息: 我使用的服务引用的不的类型中引用大会的再利用,如在客户端MyClass类*的 DTO 的*会产生一个不知道在服务器端类的MyClass
additional information: I use a service reference without reuse of types in referenced assemblys, e.g. on the client side the class MyClass*DTO* is generated an is not aware of the server side class MyClass
推荐答案
我发现的唯一的可能(但丑陋的,因此没有真正令人满意的)解决方案,这一步是使用 OnDeserializing
属性的反序列化的开始来设置默认值的使用字段的设定器,以确定是否所传送的值应真的被设置
The only possible (but ugly and therefore not really satisfying) solution I found this far is using the OnDeserializing
attribute to set the default values at the start of the deserialization an use the setter of a field to determine if the communicated value should realy be set.
[DataContract(Name = "MyClassDTO")]
public class MyClass
{
private string name;
public MyClass()
{
Init();
}
[DataMember]
public string Name
{
get{ return name; }
set
{
if (!String.IsNullOrEmpty(value))
{
name = value;
}
}
}
private void Init()
{
name = "Default Name";
}
[System.Runtime.Serialization.OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
Init();
}
}
这篇关于WCF服务的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!