【问题标题】:Differences in models for GET and POST requestsGET 和 POST 请求的模型差异
【发布时间】:2020-10-08 10:52:46
【问题描述】:

我正在使用 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 模型并使那里的标签可以为空,还是必须创建一个新模型才能使标签在那里可以为空?

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

【问题讨论】:

  • 我认为这里不存在任何标准。拥有单独的模型将有助于避免将来需要进行更多更改时可能出现的问题
  • 我更喜欢分开。为清楚起见,我将“class Input {...}”和“class Output {...}”嵌套在 Controller 类中。无需将参数耦合到“类似业务的对象”。
  • 为未来可能发生的变化做好准备肯定是有意义的。但是为了让一个 Property 可以为空而制作一个不同的模型似乎也很奇怪。我想出的每一个解决方案似乎都不完美。
  • @Max 我认为这是一个很好的观点,并且我认为我会采用创建单独对象的方式,除非我有强烈的动机不这样做。
  • 在这种情况下,我将使用自动映射器,然后在插入/创建/更新模型之前验证模型。如果您的 DescriptionLabel 为空,则返回相关错误(DescriptionLabel 不能为空)。如果将来可能会扩展,我会选择单独的课程。

标签: c# asp.net-core asp.net-web-api nullable c#-8.0


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多