.net core DotNetCore 3.1 Web Api空对象响应
返回具有公共属性的类实例时,将返回空的JSON对象{}。 但是,如果返回动态对象,则返回预期的响应。 我正在使用VS2019和最新补丁。 复制、创建ASP.NET Core Web API项目并选择.NET Core 3.1(LTS)作为框架的步骤。 将WeatherForecastController.cs的内容替换为我在下面包含的内容,然后运行应用程序.net core DotNetCore 3.1 Web Api空对象响应,.net-core,asp.net-core-webapi,.net Core,Asp.net Core Webapi,返回具有公共属性的类实例时,将返回空的JSON对象{}。 但是,如果返回动态对象,则返回预期的响应。 我正在使用VS2019和最新补丁。 复制、创建ASP.NET Core Web API项目并选择.NET Core 3.1(LTS)作为框架的步骤。 将WeatherForecastController.cs的内容替换为我在下面包含的内容,然后运行应用程序 using Microsoft.AspNetCore.Mvc; namespace WebApplication3.Controllers
using Microsoft.AspNetCore.Mvc;
namespace WebApplication3.Controllers
{
public class JsonResponse
{
public string Challenge;
public int Ttl;
}
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
public ActionResult Get()
{
JsonResponse rsp = new JsonResponse { Challenge = "challenge", Ttl = 1 };
return Ok(rsp); // returns { }
//return Ok(new { Challenge = "challenge", Ttl = 1 }); // returns { challenge: "challenge", ttl: 1 }
}
}
}
尝试修改
JsonResponse
类,使属性包含get
和set
访问器的声明,如下所示
public class JsonResponse
{
public string Challenge { get; set; }
public int Ttl { get; set; }
}
正如本文档中提到的,默认情况下会忽略字段。我不确定为什么公共属性需要这样做(在Core 2.1中不是问题),但这就解决了问题。