GET 和 POST 请求的模型差异

Differences in models for GET and POST requests

我正在使用 Asp .NET Core 创建 Web API,但在弄清楚如何创建我的数据模型时遇到了问题。

假设我从后端获得以下模型:

public class Author : AuditEntity
{
    public int Id { get; set; }

    [StringLength(45)]
    public string Name { get; set; } = null!;

    public Label DescriptionLabel { get; set; } = null!;

    public int DescriptionLabelId { get; set; }

    public ICollection<Quote> Quotes { get; } = new List<Quote>();
}

当我们收到 GET 请求时,我们使用以下简单模型:

public class Author
{
    public Author() {}

    public Author(Core.Entities.Author model)
    {
        Id = model.Id;
        Name = model.Name;
        DescriptionLabel = new Label(model.DescriptionLabel);
    }

    public int Id { get; set; }

    public string Name { get; set; } = null!;

    public Label DescriptionLabel { get; set; } = null!;
}

这里重要的是 DescriptionLabel 不能为空。 但是如果我想处理 POST 或 PUT 请求,我将希望能够允许 DescriptionLabel 为空。所以我的问题是,我应该只使用 GET 模型并使标签在那里可以为空,还是我必须创建一个新模型来使标签在那里可以为空?

获取和发布数据到网络的模型中的细微差别有哪些标准?api?

关于控制器内部单独输入输出的简短示例 classes。还需要注意的是每个控制器 class 只有一种方法。这是为了保持它更干净。我发现这种方法简单易读。

[ApiController]
[Route("[controller]")]
[AllowAnonymous]
public class SignIn : ControllerBase
{
    [HttpPost]
    public Output Post(Input input)
    {
        var user = Users.ValidateLoginCredentials(input.Email, input.Password);
        if (user != null)
        {
            return new Output
            {
                FirstName = user.FirstName,
                LastName = user.LastName,
                JWT = GenerateJWT(user)
            };
        }
        return null;
    }

    public class Input
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }

    public class Output
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string JWT { get; set; }
    }
}