堆栈溢出响应 API

Aug*_*que 0 c# asp.net-core asp.net-core-3.0

我正在向我的 WebApi Asp.Net Core 3.0 发送 POST 请求并收到错误堆栈溢出。为什么这个?

我的终端响应:

info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/2 POST https://localhost:5001/clients application/json 5
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
      Executing endpoint 'Cardapio.Controllers.ClientsController.Post (Cardapio)'
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
      Route matched with {action = "Post", controller = "Clients"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Post(Cardapio.Models.Client) on controller Cardapio.Controllers.ClientsController (Cardapio).
Stack overflow.
Run Code Online (Sandbox Code Playgroud)

我的控制器:

using System.Threading.Tasks;
using Cardapio.Models;
using Microsoft.AspNetCore.Mvc;

namespace Cardapio.Controllers
{
    [ApiController]
    [Route("clients")]
    public class ClientsController : Controller
    {
        [HttpPost]
        [Route("")]
        public IActionResult Post([FromBody]Client model)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            return Ok("Success");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的客户模型:

using System;
using System.ComponentModel.DataAnnotations;

namespace Cardapio.Models
{
    public class Client
    {
        [Key]
        public int Id { get; set; }

        public string Ip { get; set; }

        public string Identification { get; set; }

        public string Secrets { get; set; }

        public DateTime CreatedAt { get { return this.CreatedAt; } set { this.CreatedAt = DateTime.Now; } }
    }
}
Run Code Online (Sandbox Code Playgroud)

它是一个简单的控制器,在其他具有数据库访问权限的实体框架中没有问题。

Col*_*inM 5

您的模型是问题所在,CreatedAt正在引用自身,这将导致尝试检索或设置值的无限循环。

在 getter 和 setter 背后实现逻辑时需要支持字段。

这是一个使用支持字段的示例。

using System;
using System.ComponentModel.DataAnnotations;

namespace Cardapio.Models
{
    public class Client
    {
        private DateTime createdAt;

        [Key]
        public int Id { get; set; }

        public string Ip { get; set; }

        public string Identification { get; set; }

        public string Secrets { get; set; }

        public DateTime CreatedAt { get { return this.createdAt; } set { this.createdAt = DateTime.Now; } }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,您可以通过分配默认值来最小化这种情况,CreatedAt因为在getorset操作中没有任何特别的自定义发生。如果CreatedAt预计不会从 API 返回,那么您还可以删除set.

using System;
using System.ComponentModel.DataAnnotations;

namespace Cardapio.Models
{
    public class Client
    {
        [Key]
        public int Id { get; set; }

        public string Ip { get; set; }

        public string Identification { get; set; }

        public string Secrets { get; set; }

        public DateTime CreatedAt { get; set; } = DateTime.Now;
    }
}
Run Code Online (Sandbox Code Playgroud)