Skip to content

Instantly share code, notes, and snippets.

@antonydenyer
Created September 20, 2012 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonydenyer/3756013 to your computer and use it in GitHub Desktop.
Save antonydenyer/3756013 to your computer and use it in GitHub Desktop.
ValidationFeature ServiceStack
public class ValidationFeature : IPlugin
{
private readonly IErrorResponseFactory _errorResponseFactory;
public ValidationFeature(IErrorResponseFactory errorResponseFactory)
{
_errorResponseFactory = errorResponseFactory;
}
public static bool Enabled { private set; get; }
/// <summary>
/// Activate the validation mechanism, so every request DTO with an existing validator
/// will be validated.
/// </summary>
/// <param name="appHost">The app host</param>
public void Register(IAppHost appHost)
{
Enabled = true;
var filter = new ValidationFilters(_errorResponseFactory);
appHost.RequestFilters.Add(filter.RequestFilter);
}
}
public class ValidationFilters
{
private readonly IErrorResponseFactory _errorResponseFactory;
public ValidationFilters(IErrorResponseFactory errorResponseFactory)
{
_errorResponseFactory = errorResponseFactory;
}
public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
{
var validator = ValidatorCache.GetValidator(req, requestDto.GetType());
if (validator != null)
{
var ruleSet = req.HttpMethod;
var validationResult = validator.Validate(
new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet)));
if (validationResult.IsValid) return;
var errorResponse = _errorResponseFactory.CreateErrorResponse(requestDto, validationResult.ToErrorResult());
res.WriteToResponse(req, errorResponse);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment