![](/img/trans.png)
[英]How to vary the required fields for POST and PUT in Swashbuckle?
[英]How to make a property required on POST but not on PUT requests
假设我有一个用户模型,该模型具有用于身份验证目的的Email
和Password
属性,如下所示:
public class User
{
public long Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
我的目标是使这些属性仅在POST请求上才需要,而在PUT上则不需要。 即:创建新用户需要电子邮件和密码字段。 但是在编辑时,我可以忽略这些属性。 我知道可以存档此目标,以便在发布时从“电子邮件”和“密码”中删除[Required]
并检查这些属性,但这似乎不是一个好习惯。
那么,对于此用例,还有更优雅的解决方案吗?
您不应将实体用作输入/输出参数。 而是创建两个单独的视图模型来表示被调用的动作:
public class User
{
public long Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
// When creating, the client cannot know the Id because it doesn't exist
public class CreateUserViewModel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
// and when updating, the Id is required but not the Email nor the Password
public class UpdateUserViewModel
{
[Required]
public long Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
当然,由于您正在创建API,因此“视图模型”可能没有多大意义。 您可以改用数据传输对象(DTO)术语。
一种建议是使用视图模型。 在您的情况下,您可能拥有一个RegisterViewModel,它从模型中获取所有值,然后您可能拥有一个不包含电子邮件和密码的EditViewModel。 在控制器中,您的编辑功能可以替换其他字段的旧值,也可以忽略它们。
https://www.codeproject.com/Articles/1174826/Using-MVVM-in-MVC-Applications-Part
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.