SortOrderValidatorAttribute is a custom ASP.NET validation attribute for query values that must match one of a configured set of sort-order strings. It accepts ASC and DESC by default, returns validation success for an exact match, and reports an error otherwise. section 6.1.3
Implement the attribute by extending the standard validation mechanism:
- Create an Attributes/SortOrderValidatorAttribute.cs file and derive the class from ValidationAttribute. section 6.1.3
- Expose an AllowedValues string array, initializing it with ASC and DESC so callers can customize the accepted values. section 6.1.3
- Override IsValid, cast the input to a string, check it against AllowedValues, and return ValidationResult.Success or a formatted ValidationResult error. section 6.1.3
- Apply [SortOrderValidator] to the sortOrder endpoint parameter, alongside its default value of ASC. section 6.1.3
Board-game API sort order
A GET /BoardGames action can decorate its sortOrder parameter with [SortOrderValidator]. The default ASC value remains valid, while an unsupported value produces a validation error. Customize the message with ErrorMessage or extend AllowedValues when another database supports a different ordering token. section 6.1.3
Listing 6.1 SortOrderValidatorAttribute
using System.ComponentModel.DataAnnotations;
namespace MyBGList.Attributes
{
public class SortOrderValidatorAttribute : ValidationAttribute
{
public string[] AllowedValues { get; set; } =
new[] { "ASC", "DESC" };
public SortOrderValidatorAttribute()
: base("Value must be one of the following: {0}.") { }
protected override ValidationResult? IsValid(
object? value,
ValidationContext validationContext)
{
var strValue = value as string;
if (!string.IsNullOrEmpty(strValue)
&& AllowedValues.Contains(strValue))
return ValidationResult.Success;
return new ValidationResult(
FormatErrorMessage(string.Join(",", AllowedValues))
);
}
}
}
Use the complete implementation as a compact reference for the configurable values, constructor message, IsValid override, and ValidationResult handling. section 6.1.3
Validation metadata does not automatically describe the constraint in OpenAPI. A SortOrderFilter implementing IParameterFilter can inspect the attribute and add a pattern such as ^ASC$|^DESC$ to swagger.json; register the filter with AddSwaggerGen. section 6.1.4
