Skip to content

Instantly share code, notes, and snippets.

@jamescrowley
Last active September 29, 2019 09:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamescrowley/b8c0c006e7b00e28cbbf to your computer and use it in GitHub Desktop.
Save jamescrowley/b8c0c006e7b00e28cbbf to your computer and use it in GitHub Desktop.
Validating JSON with ASP.NET request validation
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