繁体   English   中英

ASP.NET 核心 - 如何在发送 Email 之前检查来自给定第三方 API 的字段是否存在

[英]ASP.NET Core - How to check if a field exists from a given third party API before sending Email

在我的 ASP.NET Core-6 Web API 给我一个第三方 API 消费然后返回账户明细。 我正在使用 HttpClient。

api:

https://api.thirdpartycompany.com:2233/UserAccount/api/AccountDetail?accountNumber=

在 appsettings.json 我有:

"Endpoints": {
  "customerUrl": "https://api.thirdpartycompany.com:2233/UserAccount/api/AccountDetail?accountNumber="
}

数据传输协议:

public class GetCustomerDetailDto
{
    public class CustomerDetail
    {
        public string AccountNumber { get; set; }
        public string Fullname { get; set; }
        public string EmailAddress { get; set; }
    }
}

然后我有这个数据实用程序:

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 CustomerDetail GetCustomerDetail(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 = _myClient.GetAsync(custAccountNoUrl).Result;
            if (response.IsSuccessStatusCode)
            {
                var stringResult = response.Content.ReadAsStringAsync().Result;
                responseResults = JsonConvert.DeserializeObject<CustomerDetail>(stringResult);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError($"An Error occured " + ex.ToString());
        }
        return responseResults;
    }
}

然后这是实现:

public async Task<Response<string>> CreateCustomerDetailAsync(CreateDto requestDto)
{
    var response = new Response<string>();
    var accDetail = _dataAccess.GetCustomerDetail(requestDto.DrAccountNumber);
    if (accDetail.EmailAddress != null)
    {
       var accountName = accDetail.Fullname;
       var emailAddress = accDetail.EmailAddress.ToLower();
       var mailBody = await EmailBodyBuilder.GetCustomerEmailBody(accountName, emailTempPath: "wwwroot/files/Html/CustomerEmail.html");
       var mailRequest = new MailRequest()
       {
          Subject = "Customer Notification",
          Body = mailBody,
          ToEmail = emailAddress
       };
       bool emailResult = await _mailService.SendEmailAsync(mailRequest);
       if (emailResult)
       {
           response.StatusCode = (int)HttpStatusCode.OK;
           response.Successful = true;
           response.Message = "Successful!";
           return response;
       }
    }
}

从第三方给出的 API 来看,有时候客户没有 email 地址,那么 EmailAddress 字段根本不会出现在响应中。

所以这让我在这里得到错误:

bool emailResult = await _mailService.SendEmailAsync(mailRequest);

我试过了

如果 (accDetail.EmailAddress != null)

但这并没有解决问题。

利用

public async Task<Response<string>> CreateCustomerDetailAsync(CreateDto requestDto)  

每当 EmailAddress 字段不存在或它是 null 时,如何使应用程序根本不发送 email?

谢谢

我试着在我身边测试,我有一个 model:

public class ProfileModel
    {
        public string DisplayName { get; set; }
        public int age { get; set; }
        public string content { get; set; }
    }

我还有一个 API,它将返回一个 JSON 字符串。

public async Task<string> GetAsync()
        {
            var name = "user1";
            string a = "{\"displayName\":\""+ name +"\",\"age\":18}";
            return a;
        }

这就是我处理 API 响应的方式。

var httpClient = _httpClientFactory.CreateClient();
var response = await httpClient.SendAsync(httpRequestMessage);
var res = "";
string name = "aa";
if (response.StatusCode == HttpStatusCode.OK)
{
    res = await response.Content.ReadAsStringAsync();
    ProfileModel profile = JsonConvert.DeserializeObject<ProfileModel>(res);
    if (profile.content != null)
        name = profile.DisplayName;
}
return "hello" + name;

在我的ProfileModel中,我定义了DisplayName, age, content属性。 if (profile.content != null)对我有用,因为我没有在 JSON 响应中设置它。 所以我认为你可以调试你的代码来找到你的 API 响应发生了什么, checking if the API response met the model you used

顺便说一句,如果问题与 JSON 字符串响应不包含EmailAddress属性的转换有关,我认为您也可以尝试在GetCustomerDetailDto中设置您的EmailAddress ,如下所示,

public string EmailAddress { get; set; } = "DefaultContent";

那么EmailAddress不会是 null,你可以检查if (accDetail.EmailAddress != "DefaultContent")

此外,由于响应是一个字符串,我们还可以检查字符串是否包含属性名称,在您的场景中,它是if (stringResult.Contains("EmailAddress"))

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM