簡體   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