Created
September 20, 2012 13:45
-
-
Save antonydenyer/3756013 to your computer and use it in GitHub Desktop.
ValidationFeature ServiceStack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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