我是 asp.net 核心 web api 的新手。我想為我的學校專案制作公告模塊。我想做的是管理員可以根據角色或目標用戶或目標部分發送公告。當請求到來時,它必須至少包含一個非空值,我怎樣才能在類屬性中實作這一點。
public class Announcement
{
public int Id { get; set; }
public string Title { get; set; }
public string Detail { get; set; }
public DateTime Date { get; set; }
public string? Attachment { get; set; }
public AppUser Poster { get; set; }
public string PosterUserId { get; set; }
public AppUser? Receiver { get; set; }
public string? ReceiverUserId { get; set; }
public Section? Section { get; set; }
public int? SectionId { get; set; }
public IdentityRole? Role { get; set; }
public string? RoleId { get; set; }
}
我可以在控制器中實作這一點,但是,是否有任何方法可以使用,以便模型系結器在其中三個為空時拒絕它。
uj5u.com熱心網友回復:
按照@Rand Random 鏈接的檔案進行。您想讓您的類成為一個 IValidatableObject,然后實作 Validate 方法。是這樣的:
public class Announcement : IValidatableObject
{
...
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (IdentityRole == null && Section == null && Receiver == null)
{
yield return new ValidationResult(
$"You must have at least one field of Role, Target User, or Target Section selected.",
new[] { nameof(IdentityRole), nameof(Section), nameof(Receiver) });
}
}
}
uj5u.com熱心網友回復:
例如,您只需在 dto 類或模型類中宣告
public string Title { get; set; } = string.Empty;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/536428.html
