You can use a model validation attribute to validate a parameter:
Create a validation attribute to ensure your string only has numeric characters by inheriting from System.ComponentModel.DataAnnotations.ValidationAttribute and overriding ValidationResult to prohibit alphabet or symbol (i.e. non-numeric) characters (you can loop through each character and compare it against 0-9, but it's cleaner to use a regular expression here):
using System.ComponentModel.DataAnnotations.ValidationAttribute;
public class NumericStringAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!ValidationRegex.IsMatch(value.ToString()))
{
return new ValidationResult("Numeric field must not have a non-numeric character.");
}
return ValidationResult.Success;
}
// Keep the expression compiled to improve performance.
private static readonly Regex ValidationRegex = new Regex(@"^[0-9]*$", RegexOptions.Compiled);
}
Now you can apply this attribute to your parameter:
public async Task<ActionResult<Schedd>> GetSchedd([NumericString] string id)
This will cause the framework to set ModelState.IsValid to false if the validation fails, which you can now check inside the function body and return a bad request as required.
if (!ModelState.IsValid)
{
return BadRequest();
}
This part is not necessary if you've applied the ApiControllerAttribute to your controller, because then validation errors are automatically handled by the framework with a BadRequest.