使用Ardalis API Endpoints返回空响应的问题求助
Ardalis API接口调试有数据但Swagger返回空响应的解决方案
问题背景
使用Ardalis API Endpoints实现接口时,调试确认数据库查询能获取到数据,但Swagger始终返回空响应,即使返回单个元素也无效。相关代码如下:
GetTeams接口代码:
public class GetTeams : EndpointBaseAsync.WithoutRequest.WithActionResult<IEnumerable<TeamsResult>> { private readonly ITeamsRepository _teamsRepository; public GetTeams(ITeamsRepository teamsRepository) { _teamsRepository = teamsRepository; } [HttpGet()] [Route("/teams")] [SwaggerOperation( Summary = "Gets a list of all the available teams", Description = "Gets list of all the teams", OperationId = "Teams.Get", Tags = new[] { "TeamEndpoint" }) ] public override async Task<ActionResult<IEnumerable<TeamsResult>>> HandleAsync(CancellationToken cancellationToken = default) { var teams = await _teamsRepository.GetAllTeams(); return Ok(teams); } }
TeamsRepository代码:
private readonly string _connectionStringSoccerApi; public TeamsRepository(IOptions<ConnectionStringConfig> connectionString) { _connectionStringSoccerApi = connectionString.Value.SoccerApi; } public async Task<IEnumerable<TeamsResult>> GetAllTeams() { using var connection = new SqlConnection(_connectionStringSoccerApi); string getAllTeamsQuery = "Select * from Teams"; return await connection.QueryAsync<TeamsResult>(getAllTeamsQuery); }
TeamsResult类代码:
public class TeamsResult { public string Name; }
问题原因
ASP.NET Core默认使用的System.Text.Json序列化器默认只序列化公共属性(带get/set的成员),而TeamsResult中的Name是公共字段,不是属性,因此序列化时会被忽略,最终返回的JSON为空对象/数组,导致Swagger显示空响应。
解决方案
方案1:将字段改为属性(推荐)
修改TeamsResult类,把Name字段改为带getter和setter的属性:
public class TeamsResult { public string Name { get; set; } }
方案2:配置序列化器包含字段(仅特殊场景使用)
如果必须保留字段,可以在Program.cs中配置JSON序列化器,使其包含公共字段:
builder.Services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.IncludeFields = true; });
验证
修改后重新运行项目,Swagger将正确返回包含Name数据的响应,因为序列化器现在能识别并处理对应的成员。
内容的提问来源于stack exchange,提问作者Uribe2304
相关产品推荐
相关产品推荐

