Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

c# - Fresh ASP.NET Core API returns empty JSON objects

I have made a .NET Core Web API project to test it out.

My problem is, that the API returns an empty JSON object, when I request the endpoint, which is located at "/api/cars/123" for instance. This happens no matter what kind of object I put in, unless it's any primitive datatype, or an array thereof. The response is always:

{}

The configuration of the application is completely default, on a fresh Visual Studio 2017 installation.

I have the following classes:

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

    }
}

Am I missing something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order for the JsonSerializer to be able to see and serialize your properties, they need to be public:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...