[英]Fresh ASP.NET Core API returns empty JSON objects
我制作了一个 .NET Core Web API 项目来测试它。
我的问题是,当我请求位于“/api/cars/123”的端点时,API 返回一个空的 JSON 对象。 无论我放入什么样的对象都会发生这种情况,除非它是任何原始数据类型或其数组。 响应总是:
{}
在全新的 Visual Studio 2017 安装中,应用程序的配置是完全默认的。
我有以下课程:
汽车.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;
}
}
}
汽车控制器.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" ));
}
}
}
我错过了什么吗?
为了让 JsonSerializer 能够查看和序列化您的属性,它们需要是公开的:
public int Id { get; private set; } //the setters can be private
public string Make { get; set; }
public string Model { get; set; }
通过添加配置试试这个
services.AddControllersWithViews().AddNewtonsoftJson();
....AddNewtonsoftJson() 这应该可以解决问题。
尝试像这样定义您的实体:
namespace Ex6.Entities
{
public class Car
{
public int Id { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public Car(int _Id, string _Make, string _Model)
{
Id = _Id;
Make = _Make;
Model = _Model;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.