| name | servicestack-validation |
| description | Applies FluentValidation and ServiceStack validation filters correctly. |
ServiceStack Validation
ServiceStack uses FluentValidation to provide a declarative way to validate Request DTOs.
Defining Validators
- Create a class that inherits from
AbstractValidator<TRequestDto>.
- Define rules in the constructor using the
RuleFor syntax.
- Place validators in the
ServiceInterface project (usually).
public class GetCustomerValidator : AbstractValidator<GetCustomer>
{
public GetCustomerValidator()
{
RuleFor(r => r.Id).GreaterThan(0);
}
}
Registration
Validators are automatically registered in the IoC container if you use the ValidationFeature.
Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof(MyServices).Assembly);
Validation Context
- Global Filters: The
ValidationFeature installs a global request filter that automatically executes validators before the service.
- Error Responses: ServiceStack automatically converts validation failures into a
ResponseStatus inside your Response DTO.
Manual Validation
While automatic validation is preferred, you can manually validate if needed:
var results = validator.Validate(request);
if (!results.IsValid)
throw results.ToException();
Best Practices
- Validate Input ONLY: Use FluentValidation for validating the Request DTO structure, not complex business rules that require database state (though it's possible, keep it simple).
- Consistent Error Codes: Use
.WithErrorCode() for custom error codes that clients can easily switch on.
- Client Metadata: Validation rules are exposed in the metadata, allowing clients (like TypeScript) to know the rules.