Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net core DotNetCore 3.1 Web Api空对象响应_.net Core_Asp.net Core Webapi - Fatal编程技术网

.net core DotNetCore 3.1 Web Api空对象响应

.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

返回具有公共属性的类实例时,将返回空的JSON对象{}。 但是,如果返回动态对象,则返回预期的响应。 我正在使用VS2019和最新补丁。 复制、创建ASP.NET Core Web API项目并选择.NET Core 3.1(LTS)作为框架的步骤。 将WeatherForecastController.cs的内容替换为我在下面包含的内容,然后运行应用程序

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中不是问题),但这就解决了问题。