You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现SOAP输出时根据ContactInfo值隐藏指定属性的方法

实现方案

你可以利用.NET 序列化器原生支持的 ShouldSerialize 约定实现动态属性忽略,SOAP 服务默认使用的 XmlSerializer 和 DataContractSerializer 都支持该规则,无需引入第三方组件。

步骤1:修改 CustomerPermission 实体类

首先将值类型的 CallStatus 改为可空类型,避免值类型默认值导致非预期输出,同时添加序列化判断逻辑:

public class CustomerPermission {
    public string ContactInfo { get; set; }
    // 改为可空布尔,支持空值判断
    public Boolean? CallStatus { get; set; }
    public string CallModifiedDate { get; set; }
    public Boolean SalesStatus { get; set; }
    public string SalesModifiedDate { get; set; }

    // 序列化时判断是否输出CallStatus属性
    public bool ShouldSerializeCallStatus()
    {
        // 仅当ContactInfo不是邮箱时才输出
        return !IsEmail(ContactInfo);
    }

    // 序列化时判断是否输出CallModifiedDate属性
    public bool ShouldSerializeCallModifiedDate()
    {
        return !IsEmail(ContactInfo);
    }

    // 邮箱格式判断逻辑,可替换为更严谨的正则校验
    private bool IsEmail(string contact)
    {
        if (string.IsNullOrWhiteSpace(contact))
            return false;
        // 简单判断含@即为邮箱,如需更严格校验可换成正则:
        // return System.Text.RegularExpressions.Regex.IsMatch(contact, @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$");
        return contact.Contains("@");
    }
}

步骤2:修正数据填充逻辑

原代码存在字符串直接赋值给布尔值的类型错误,同时补充 DBNull 处理逻辑:

List<CustomerPermission> customerPermission = new List<CustomerPermission>();
foreach (DataRow dr in dt.Rows)
{
    CustomerPermission cusPer = new CustomerPermission();
    cusPer.ContactInfo = dr["contact_info"].ToString();
    // 处理DBNull和类型转换
    cusPer.CallStatus = dr["call_status"] == DBNull.Value ? null : (bool?)Convert.ToBoolean(dr["call_status"]);
    cusPer.CallModifiedDate = dr["call_date"] == DBNull.Value ? null : dr["call_date"].ToString();
    cusPer.SalesStatus = Convert.ToBoolean(dr["sales_status"]);
    cusPer.SalesModifiedDate = dr["sales_date"].ToString();
    customerPermission.Add(cusPer);
}

效果说明

修改完成后,SOAP 接口序列化返回时会自动执行 ShouldSerialize 开头的方法:

  • 当 ContactInfo 是手机号格式时,返回所有属性
  • 当 ContactInfo 是邮箱格式时,自动跳过 CallStatus 和 CallModifiedDate 两个属性的输出,完全符合你预期的返回格式

内容的提问来源于stack exchange,提问作者Kara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 11:15:07