使用自定义错误消息在WCF服务中进行验证

时间:2019-01-30 12:19:57

标签: validation wcf data-annotations

我有如下数据合同。如果名称为空,我想返回一个自定义错误消息。我该如何实现? 合同:

[DataContract]
    public class Employee
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]

        public string Name { get; set; }
    }

响应: 错误代码:111 错误描述:null ErrorText:null StateCode:空

1 个答案:

答案 0 :(得分:0)

您要做的是查看故障合同,

可以在网上找到一些链接

  1. https://www.c-sharpcorner.com/UploadFile/788083/how-to-implement-fault-contract-in-wcf/
  2. https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/fault-contract
  3. http://www.topwcftutorials.net/2014/07/wcf-fault-contract.html

但是,如果这对于您想要实现的目标来说有点过分了,您可以看看DataAnnotation,放在

[DataMember]
[Required]
public string Name { get; set; }

应该是强制用户为

创建值所需的全部
  

名称

还请注意,使用自定义错误消息的[Required]属性有重载

[Required(ErrorMessage="You have not supplied a value for the Name parameter")]

您也可以将其与

结合使用
[StringLength(20, ErrorMessage = "The Name value cannot exceed 20 characters. ")]

这看起来不像

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