GET和POST请求的模型差异

问题描述

我正在使用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不能为null。 但是,如果我想处理POST或PUT请求,我将希望能够允许DescriptionLabel为null。所以我的问题是,我应该只使用GET模型并将标签设为可为空,还是必须创建新模型以使标签在那里为可为空?

对于将数据获取和发布到网络api的模型中的微小差异有哪些标准?

解决方法

关于控制器内部单独的输入输出类的简短示例。还需要注意的关键是每个控制器类只有一个方法。这是为了保持清洁。我发现这种方法简单易懂。

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