Last active
September 29, 2019 09:48
-
-
Save jamescrowley/b8c0c006e7b00e28cbbf to your computer and use it in GitHub Desktop.
Validating JSON with ASP.NET request validation
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 JsonValidatingModelBinder : DefaultModelBinder | |
{ | |
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) | |
{ | |
var result = base.BindModel(controllerContext, bindingContext); | |
if (!IsJsonRequest(controllerContext)) | |
{ | |
return result; | |
} | |
if (!bindingContext.ModelMetadata.RequestValidationEnabled) | |
{ | |
return result; | |
} | |
if (result != null) | |
{ | |
EnsureRequestFieldIsValid(controllerContext, result); | |
} | |
return result; | |
} | |
static void EnsureRequestFieldIsValid(ControllerContext controllerContext, object result) | |
{ | |
int index; | |
// abusing RequestValidationSource enum | |
if (!RequestValidator.Current.InvokeIsValidRequestString( | |
controllerContext.HttpContext.ApplicationInstance.Context, | |
result.ToString(), RequestValidationSource.Form, null, out index)) | |
{ | |
throw new HttpRequestValidationException( | |
"A potentially dangerous value was detected from the client "); | |
} | |
} | |
static bool IsJsonRequest(ControllerContext controllerContext) | |
{ | |
return controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment