2017-06-01 38 views
1

我製作了一個.NET Core Web API項目來測試它。新鮮的ASP.NET Core API返回空的JSON對象

我的問題是,例如,當我請求位於「/ api/cars/123」的端點時,API返回空的JSON對象。無論我輸入什麼樣的對象,都會發生這種情況,除非它是任何原始數據類型或其數組。該反應總是:

{} 

應用程序的配置是完全默認情況下,一個新的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; 
     } 
    } 
} 

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")); 
     } 

    } 
} 

我缺少的東西?

+0

你可以嘗試刪除該「生產」行?我從來沒有見過,也不知道它是什麼 –

+0

是的,再次更新問題。它沒有區別,但:S –

+0

如果你在返回線上放置一個斷點,它會被擊中?順便說一下,您使用哪種工具進行測試? –

回答

2

爲了使JsonSerializer能夠看到和序列化的屬性,他們需要的是公衆:

public int Id { get; private set; } //the setters can be private 
public string Make { get; set; } 
public string Model { get; set; }