新鲜的ASP.NET Core API返回空的JSON对象 [英] Fresh ASP.NET Core API returns empty JSON objects

查看:60
本文介绍了新鲜的ASP.NET Core API返回空的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经制作了一个.NET Core Web API项目来对其进行测试.

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

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

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:

{}

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

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

我有以下课程:

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

    }
}

我想念什么吗?

推荐答案

为了使JsonSerializer能够查看和序列化您的属性,它们必须是公开的:

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

这篇关于新鲜的ASP.NET Core API返回空的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆