In an ASP.NET Web API (.NET7) project, I have a data model as follows:
public class MeetupGroup
{
public string GroupName { get; set; }
public string MeetingPlace { get; set; }
public ICollection<GroupMember> GroupMembers { get; set; }
}
public class GroupMember
{
public string Email { get; set; }
public string Name { get; set; }
}
We want to enforce the requirement that a Meetup Group must have at least one member at the time of creation.
I'd like to do this with a custom model Validation Attribute, rather than in the controller:
public class MembersNotEmptyAttribute : ValidationAttribute
{
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
var members = (GroupMember)value!;
if (!members.Any())
{
return new ValidationResult("At least one member must be present");
}
return ValidationResult.Success;
}
}
But that's just for creating a new Meetup Group (HTTP POST).
We also need to provide an Update method (HTTP PATCH), but there is no requirement that they provide a Group Member for that. They would just be updating the GroupName and MeetingPlace properties. There will be other methods to add/remove or modify group members.
Is there a way to do this? Or am I stuck enforcing this in the controller?
Thanks.
According to your description, if you don't want to let the patch method still need follow the custom validation, I suggest you could put some condition inside the MembersNotEmptyAttribute class.
You could get the httpmethod by injecting the HttpContextAccessor and get current request context inside the MembersNotEmptyAttribute.
If current request http method is PATCH, then you could just check the groupname and return the valdation result success.
More details, you could refer to below codes:
public class MembersNotEmptyAttribute : ValidationAttribute
{
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
var httpContextAccessor = (IHttpContextAccessor)validationContext.GetService(typeof(IHttpContextAccessor));
//get current request's http method
var re = httpContextAccessor.HttpContext.Request.Method;
ICollection<GroupMember> members = (ICollection<GroupMember>)value!;
if (re == "PATCH")
{
//here you could do the custom validation for the PATCH request
}
else
{
//here you could do the custom vaidation for the not PATCH request
if (!members.Any())
{
return new ValidationResult("At least one member must be present");
}
}
return ValidationResult.Success;
}
}
Result: