For .NET Core (and maybe earlier versions) you can also create a custom attribute to perform the range validation for ease of reuse:
public class Id : ValidationAttribute
{
protected override ValidationResult IsValid(
object value,
ValidationContext validationContext)
{
return Convert.ToInt32(value) > 0 ?
ValidationResult.Success :
new ValidationResult($"{validationContext.DisplayName} must be an integer greater than 0.");
}
}
Use the Id attribute like this in your model:
public class MessageForUpdate
{
[Required, Id]
public int UserId { get; set; }
[Required]
public string Text { get; set; }
[Required, Id]
public int ChannelId { get; set; }
}
When the Id is <= 0
this error message is returned:
UserId must be an integer greater than 0.
No need to verify that the value is less than int.MaxValue (although it is nice to display that in the message) because the API will return this error by default before it gets this far even if the value is int.MaxValue + 1:
The JSON value could not be converted to System.Int32