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

kwvwclae  于 4个月前  发布在  .NET
关注(0)|答案(3)|浏览(77)

我已经做了一个.NET Core Web API项目来测试它。
我的问题是,当我请求位于“/API/汽车/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;
        }
    }
}

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

    }
}


我错过了什么吗?

4uqofj5v

4uqofj5v1#

为了让JsonSerializer能够看到并序列化你的属性,它们需要是公共的:

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

字符串

m2xkgtsf

m2xkgtsf2#

由于某些原因,Text.JSON也不会序列化公共字段,所以它们需要是属性。

1l5u6lss

1l5u6lss3#

通过添加configure尝试此操作

services.AddControllersWithViews().AddNewtonsoftJson();

字符串
.AddNewtonsoftJson()这应该可以解决问题。

相关问题