ASP.NET Core Web API:如何按条件筛选第三方API返回数据
实现分支数据筛选的步骤
1. 定义数据模型
先创建对应第三方API返回数据的模型类,只保留你需要的字段(必须包含BranchType),反序列化时会自动忽略多余字段:
public class BranchDto { public int Id { get; set; } public string Name { get; set; } public string BranchType { get; set; } // 按需添加其他业务所需字段 } // 若第三方API返回的是带根节点的对象(而非直接数组),补充根模型: public class BranchApiResponse { public List<BranchDto> Branches { get; set; } }
2. 读取配置的API地址
在appsettings.json中配置第三方API地址:
{ "ThirdPartyApiSettings": { "BranchDetailsUrl": "https://第三方分支API的实际地址" } }
在Program.cs中注册配置与HttpClient:
// 绑定配置类 builder.Services.Configure<ThirdPartyApiSettings>(builder.Configuration.GetSection("ThirdPartyApiSettings")); // 注册HttpClient用于调用第三方API builder.Services.AddHttpClient();
对应配置类:
public class ThirdPartyApiSettings { public string BranchDetailsUrl { get; set; } }
3. 调用API并筛选目标数据
在服务或控制器中注入HttpClient与IOptions<ThirdPartyApiSettings>,实现调用与筛选逻辑:
private readonly HttpClient _httpClient; private readonly ThirdPartyApiSettings _apiSettings; // 构造函数注入依赖 public BranchProcessor(HttpClient httpClient, IOptions<ThirdPartyApiSettings> apiSettings) { _httpClient = httpClient; _apiSettings = apiSettings.Value; } public async Task ProcessTargetBranchesAsync() { // 发起第三方API请求 var response = await _httpClient.GetAsync(_apiSettings.BranchDetailsUrl); response.EnsureSuccessStatusCode(); // 确保请求成功 // 反序列化返回数据 var apiResponse = await response.Content.ReadFromJsonAsync<BranchApiResponse>(); if (apiResponse?.Branches == null) return; // 筛选指定分支类型的数据 var targetBranches = apiResponse.Branches .Where(b => b.BranchType == "Human Resource" || b.BranchType == "Production") .ToList(); // 执行后续新增/更新操作 foreach (var branch in targetBranches) { // 此处替换为你的业务逻辑,比如写入数据库或更新现有数据 // await _branchRepository.UpsertAsync(branch); } }
额外优化提示
- 若第三方API直接返回分支数组(无包装根节点),反序列化时直接使用
List<BranchDto>即可:var branches = await response.Content.ReadFromJsonAsync<List<BranchDto>>(); - 如需忽略大小写匹配
BranchType,改用StringComparison.OrdinalIgnoreCase:.Where(b => string.Equals(b.BranchType, "Human Resource", StringComparison.OrdinalIgnoreCase) || string.Equals(b.BranchType, "Production", StringComparison.OrdinalIgnoreCase)) - 建议添加异常捕获逻辑,处理API请求失败、反序列化失败等场景,避免程序崩溃。
内容的提问来源于stack exchange,提问作者Ayobamilaye
相关产品推荐
相关产品推荐

