[英]Validation in WCF Service with custom error message
I am having a Data Contract as below. 我有如下数据合同。 I want to return a custom error message if Name is empty.
如果名称为空,我想返回一个自定义错误消息。 How can i achieve that?
我该如何实现? Contract:
合同:
[DataContract]
public class Employee
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
}
Response: ErrorCode: 111 ErrorDesc: null ErrorText: null StateCode: null 响应:错误代码:111错误描述:空错误文本:空状态代码:空
What you want to do is look at Fault Contracts, 您要做的就是查看故障合同,
A few links can be found on the net 网上可以找到一些链接
But if that is a bit too much for what you want to achieve, you can look at DataAnnotation , putting 但是,如果这对于您想要实现的目标来说有点过多,则可以查看DataAnnotation ,
[DataMember]
[Required]
public string Name { get; set; }
Should be all that is required to force the user to create a value for 应该是迫使用户为
Name
名称
Also note that there is an overload to the [Required] Attribute that uses a custom error message 另请注意,使用自定义错误消息的[Required]属性有重载
[Required(ErrorMessage="You have not supplied a value for the Name parameter")]
You can also combine this with 您也可以将其与
[StringLength(20, ErrorMessage = "The Name value cannot exceed 20 characters. ")]
This would not look like 这看起来像
[DataContract]
public class Employee
{
[DataMember]
public int Id { get; set; }
[DataMember]
[StringLength(20, ErrorMessage = "The Name value cannot exceed 20 characters. ")]
[Required(ErrorMessage="You have not supplied a value for the Name parameter")]
public string Name { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.