【问题标题】:DotNetCore 3.1 Web Api empty object responseDotNetCore 3.1 Web Api 空对象响应
【发布时间】:2021-06-13 07:18:43
【问题描述】:

返回具有公共属性的类实例时,会返回一个空的 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 }
        }   
    }
}

【问题讨论】:

    标签: .net-core asp.net-core-webapi


    【解决方案1】:

    尝试修改您的 JsonResponse 类以使属性包含 getset 访问器的声明,如下所示。

    public class JsonResponse
    {
        public string Challenge { get; set; }
    
        public int Ttl { get; set; }
    }
    

    正如本文档中提到的"Serialization behavior",默认情况下会忽略字段。

    【讨论】:

    • 我不知道为什么公共财产需要这样做(在 Core 2.1 中这不是问题),但确实成功了。
    猜你喜欢
    • 2019-05-17
    • 2019-02-13
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2015-10-09
    • 1970-01-01
    相关资源
    最近更新 更多