【问题标题】:Property 'JsonResult.SerializerSettings' must be an instance of type 'System.Text.Json.JsonSerializerOptions'属性“JsonResult.SerializerSettings”必须是“System.Text.Json.JsonSerializerOptions”类型的实例
【发布时间】:2020-07-23 01:00:45
【问题描述】:

我正在开发一个页面,显示所有离开类型选项值的网络网格(这是一个包含 id、离开类型和状态的模型)。在我的控制器中,我在下面写了一些东西。

运行代码后出现运行时错误

InvalidOperationException:属性“JsonResult.SerializerSettings”必须是“System.Text.Json.JsonSerializerOptions”类型的实例

我试图用谷歌搜索它,但我不明白这个问题,我想就如何解决这个问题寻求建议。

谢谢。

public class OptLeaveTypeController : Controller
{
        private readonly theManagerContext _context;

        public OptLeaveTypeController(theManagerContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult GetLeaveTypes()
        {         
                var leaveTypes = _context.OptLeaveType.OrderBy(a => a.LeaveTypeId).ToList();
                return Json(new { data = leaveTypes }, System.Web.Mvc.JsonRequestBehavior.AllowGet);
        }
}

【问题讨论】:

  • 您使用的是 .net core 3.1 吗?
  • 我使用的是 .net core 3.0。谢谢

标签: c# json asp.net-mvc .net-core asp.net-core-mvc


【解决方案1】:

1) .NET CORE MVC:-

    public IActionResult GetLeaveTypes()
    {         
            var leaveTypes = _context.OptLeaveType.OrderBy(a => a.LeaveTypeId).ToList();
            return Json(new { data = leaveTypes });
    }

或

    public IActionResult GetLeaveTypes()
    {         
            var leaveTypes = _context.OptLeaveType.OrderBy(a => a.LeaveTypeId).ToList();
            return new JsonResult(new { data = leaveTypes });
    }

2) .NET MVC:-

    public ActionResult GetLeaveTypes()
    {         
            var leaveTypes = _context.OptLeaveType.OrderBy(a => a.LeaveTypeId).ToList();
            return Json(new { data = leaveTypes }, System.Web.Mvc.JsonRequestBehavior.AllowGet);
    }

【讨论】:

  • 只想问为什么结果返回的字段名是小写开头的?我的数据库字段和模型名称以大写字母开头,例如 LeaveTypeId、LeaveType...等。谢谢 {"data":[{"leaveTypeId":1,"leaveType":"年假","status":"1"},{"leaveTypeId":2,"leaveType":"病假","status ":"1 "}]}
  • @George Now .NET CORE JSON 默认现在是 camelCase(这是 JSON 约定)。如果您需要/希望所有 JSON 输出都使用 PascalCase,请参阅 --stackoverflow.com/questions/38728200/…
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 2020-11-08
  • 2020-11-04
  • 1970-01-01
  • 2021-06-11
  • 2019-04-22
  • 2011-03-01
  • 2017-09-30
相关资源
最近更新 更多