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

ASP.NET Core Web API:第三方API无Email字段时禁止发送邮件

解决方案

1. 优化DTO的反序列化行为(可选)

默认情况下Newtonsoft.Json会在JSON缺少对应字段时将属性设为null,为了明确控制字段缺失或空值的处理逻辑,可给EmailAddress属性添加特性:

public class GetCustomerDetailDto
{
    public class CustomerDetail
    {
        public string AccountNumber { get; set; }
        public string Fullname { get; set; }
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore)]
        public string EmailAddress { get; set; }
    }
}

2. 修复DataUtil的异步调用问题

原方法使用.Result阻塞异步操作,易引发死锁,改为异步实现:

public class DataUtil : IDataUtil
{
    private readonly IConfiguration _config;
    private readonly ILogger<DataUtil> _logger;
    private readonly HttpClient _myClient;

    public DataUtil(IConfiguration config, ILogger<DataUtil> logger, HttpClient myClient)
    {
        _config = config;
        _logger = logger;
        _myClient = myClient;
    }

    public async Task<CustomerDetail> GetCustomerDetailAsync(string accountNumber)
    {
        var responseResults = new CustomerDetail();
        try
        {
            string custAccountNoUrl = _config.GetSection("Endpoints").GetValue<string>("customerUrl") + accountNumber;
            _myClient.DefaultRequestHeaders.Accept.Clear();
            _myClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = await _myClient.GetAsync(custAccountNoUrl);
            
            if (response.IsSuccessStatusCode)
            {
                var stringResult = await response.Content.ReadAsStringAsync();
                responseResults = JsonConvert.DeserializeObject<CustomerDetail>(stringResult);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error fetching customer account detail");
        }
        return responseResults;
    }
}

同时更新IDataUtil接口,将方法签名改为Task<CustomerDetail> GetCustomerDetailAsync(string accountNumber);

3. 实现CreateCustomerDetailAsync的邮件判断逻辑

使用string.IsNullOrWhiteSpace()覆盖所有无效邮箱场景(字段缺失、null、空字符串、空白字符):

public async Task<Response<string>> CreateCustomerDetailAsync(CreateDto requestDto)
{
    // 获取账户详情
    var accDetail = await _dataUtil.GetCustomerDetailAsync(requestDto.AccountNumber);

    // 执行你的业务逻辑...

    // 仅当邮箱有效时发送邮件
    if (!string.IsNullOrWhiteSpace(accDetail.EmailAddress))
    {
        var mailRequest = new MailRequest
        {
            ToEmail = accDetail.EmailAddress,
            Subject = "Your Account Information",
            Body = $"Hi {accDetail.Fullname}, your account details have been processed."
            // 补充其他邮件参数
        };
        await _mailService.SendEmailAsync(mailRequest);
    }

    return new Response<string> { Success = true, Data = "Customer detail processed successfully" };
}

核心要点

  • string.IsNullOrWhiteSpace()会同时检查null、空字符串和空白字符,完美覆盖第三方API返回的各种无效邮箱情况
  • 异步方法的改进避免了同步阻塞带来的性能问题和潜在死锁风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:15:10