liveBook · Manning

SortOrderValidatorAttribute

As explained in Building Web APIs with ASP.NET Core

SortOrderValidatorAttribute is the book's custom validation attribute that accepts only configured sort-order values.

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

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains class creation, inheritance, IsValid logic, configurable values, error messages, endpoint usage, and OpenAPI integration.
Examples
Uses ASC and DESC validation, configurable AllowedValues, custom error messages, the sortOrder parameter, and generated OpenAPI patterns.
What it assumes
Assumes familiarity with C# classes, attributes, endpoint parameters, and basic ASP.NET validation conventions.
What you can do after
Build it from scratch as a reusable validator and expose its accepted values to generated OpenAPI documentation.
How it connects
Connects ValidationAttribute, ValidationResult, regular expressions, query parameters, OpenAPI, and Swashbuckle parameter filters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.