Created
February 22, 2014 13:14
-
-
Save jamescrowley/9154663 to your computer and use it in GitHub Desktop.
Return validation errors instead of an exception for HttpRequestValidation errors
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 HtmlRequestValidationModelBinder : DefaultModelBinder | |
{ | |
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) | |
{ | |
try | |
{ | |
return base.BindModel(controllerContext, bindingContext); | |
} | |
catch (HttpRequestValidationException) | |
{ | |
var modelState = new ModelState(); | |
modelState.Errors.Add(string.Format("'{0}' contains invalid characters", bindingContext.ModelMetadata.DisplayName ?? bindingContext.ModelMetadata.PropertyName)); | |
modelState.Value = bindingContext.GetValueFromValueProvider(false); | |
bindingContext.ModelState.Add(bindingContext.ModelName, modelState); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment