新的ASP.NET Core API返回空的JSON对象

Emi*_*sen 6 c# asp.net

我已经制作了一个.NET Core Web API项目来测试它.

我的问题是,当我请求端点时,API返回一个空的JSON对象,例如位于"/ api/cars/123".无论我放入什么类型的对象,都会发生这种情况,除非它是任何原始数据类型或其数组.响应总是:

{}
Run Code Online (Sandbox Code Playgroud)

在全新的Visual Studio 2017安装中,应用程序的配置完全是默认的.

我有以下课程:

Car.cs

namespace Ex6.Entities
{
    public class Car
    {
        private int Id { get; set; }
        private string Make { get; set; }
        private string Model { get; set; }

        public Car(int Id, string Make, string Model)
        {
            this.Id = Id;
            this.Make = Make;
            this.Model = Model;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

CarsController.cs:

using Microsoft.AspNetCore.Mvc;
using Ex6.Entities;

namespace Ex6.Controllers
{
    [Route("api/[controller]")]
    public class CarsController : Controller
    {

        [HttpGet("{id}")]
        public JsonResult GetCar(int id)
        {
            return Json(new Car(1, "Toyota", "Aygo" ));
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?

SO *_*ood 11

为了让JsonSerializer能够查看和序列化您的属性,它们需要公开:

public int Id { get; private set; } //the setters can be private
public string Make { get; set; }
public string Model { get; set; }
Run Code Online (Sandbox Code Playgroud)

  • 在将旧版 WCF 转换为 WebAPI 时,我遇到了同样的问题。但是,我遇到的问题是结果类具有所有字段但没有属性。我向所有字段添加了 getter 和 setter,将它们转换为自动属性,一切正常。 (3认同)
  • 在文档中找不到这个。希望更容易找到这个答案...... (3认同)