在ASP.NET Core 3.1 Web API中自定义响应包装器可能会导致JSON响应出错。下面是一个解决方法的示例代码:
public class ApiResponse
{
public int StatusCode { get; set; }
public string Message { get; set; }
public T Data { get; set; }
}
[HttpGet]
public async Task>>> Get()
{
try
{
var data = await _yourService.GetDataAsync();
var response = new ApiResponse>
{
StatusCode = 200,
Message = "Success",
Data = data
};
return Ok(response);
}
catch (Exception ex)
{
var response = new ApiResponse>
{
StatusCode = 500,
Message = ex.Message,
Data = null
};
return StatusCode(500, response);
}
}
ConfigureServices
方法,并添加以下代码:services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
Configure
方法中使用正确的中间件顺序,以确保自定义包装器正常工作。例如,将以下代码添加到Configure
方法的开头:app.Use(async (context, next) =>
{
context.Response.Headers.Add("Content-Type", "application/json");
await next();
});
通过使用自定义响应包装器类和正确配置JSON序列化选项,您应该能够在ASP.NET Core 3.1 Web API中正确处理JSON响应。