Json/XML Request parameter schema validation
public class ValidateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
try
{
if (filterContext.HttpContext.Request.Method == "POST")
{
string requestData = string.Empty;
using (var reader = new StreamReader(filterContext.HttpContext.Request.Body))
{
filterContext.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
requestData = reader.ReadToEnd();
if (string.IsNullOrEmpty(requestData))
filterContext.Result = new BadRequestResult();
}
if (filterContext.HttpContext.Request.ContentType == "application/xml")
{
string errorMessages;
var isValidXml = IsValidXmlSchema(filterContext, requestData, out errorMessages);
if (!isValidXml)
{
var objectResult = new ObjectResult("Invalid");
filterContext.Result = objectResult;
}
}
if (filterContext.HttpContext.Request.ContentType == "application/json")
{
IList<string> errorMessages;
var isValidJson = IsValidJsonSchema(filterContext, requestData, out errorMessages);
if (!isValidJson)
{
var objectResult = new ObjectResult("Exception");
filterContext.Result = objectResult;
}
}
}
}
catch (Exception ex)
{
filterContext.Result = new BadRequestResult();
}
base.OnActionExecuting(filterContext);
}
//To validate the Json Schema with action request parameter schema
private bool IsValidJsonSchema(ActionExecutingContext filterContext, string requestData, out IList<string> errorMessages)
{
errorMessages = null;
// foreach (var postItem in filterContext.ActionArguments)
foreach (var postItem in filterContext.ActionDescriptor.Parameters)
{
Newtonsoft.Json.JsonConvert.DefaultSettings = (() =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter());
return settings;
});
Type objType = postItem.ParameterType;
JSchemaGenerator jSchemaGenerator = new JSchemaGenerator();
jSchemaGenerator.GenerationProviders.Add (new StringEnumGenerationProvider());
//jSchemaGenerator.ContractResolver = new ShouldSerializeContractResolver();
jSchemaGenerator.SchemaReferenceHandling = SchemaReferenceHandling.None;
var schemaJson = jSchemaGenerator.Generate(objType);
JSchema schema = JSchema.Parse(schemaJson.ToString().ToLower());
JObject jsonObject = JObject.Parse(requestData.ToLower());
bool isValid = jsonObject.IsValid(schema, out errorMessages);
if (!isValid)
return isValid;
}
return true;
}
//To validate the XML Schema with action request parameter schema
private bool IsValidXmlSchema(ActionExecutingContext filterContext, string requestData, out string errorMessages)
{
errorMessages = null;
foreach (var postItem in filterContext.ActionDescriptor.Parameters)
{
Type objType = postItem.ParameterType;
var schemas = new XmlSchemas();
var exporter = new XmlSchemaExporter(schemas);
var mapping = new XmlReflectionImporter().ImportTypeMapping(objType);
exporter.ExportTypeMapping(mapping);
var schemaWriter = new StringWriter();
foreach (XmlSchema schema in schemas)
{
schema.Write(schemaWriter);
}
var xsdMarkup = schemaWriter.ToString();
bool isValid = ValidateXmlSchema(requestData, xsdMarkup, out errorMessages);
if (!isValid)
return isValid;
}
return true;
}
private bool ValidateXmlSchema(string strXml, string xsdMarkup, out string errorMessages)
{
errorMessages = string.Empty;
try
{
string strErrorMessage = string.Empty;
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));
XDocument xDocument = XDocument.Parse(strXml);
xDocument.Validate(schemas, (o, e) =>
{
strErrorMessage = e.Message;
});
errorMessages = strErrorMessage;
if (errorMessages != string.Empty)
return false;
}
catch (Exception ex)
{
errorMessages = ex.Message;
return false;
}
return true;
}
}
public class est
{
[XmlElement(IsNullable =true)] // Required property setting
public HeaderNode Header { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] // Optional property setting
[XmlElement(IsNullable = false)] // Optional property setting
public ImportNode Import { get; set; }
}
public class HeaderNode
{
public string Version { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public enumAppName AppName { get; set; }
public string AppVersion { get; set; }
public string Database { get; set; }
}
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
try
{
if (filterContext.HttpContext.Request.Method == "POST")
{
string requestData = string.Empty;
using (var reader = new StreamReader(filterContext.HttpContext.Request.Body))
{
filterContext.HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
requestData = reader.ReadToEnd();
if (string.IsNullOrEmpty(requestData))
filterContext.Result = new BadRequestResult();
}
if (filterContext.HttpContext.Request.ContentType == "application/xml")
{
string errorMessages;
var isValidXml = IsValidXmlSchema(filterContext, requestData, out errorMessages);
if (!isValidXml)
{
var objectResult = new ObjectResult("Invalid");
filterContext.Result = objectResult;
}
}
if (filterContext.HttpContext.Request.ContentType == "application/json")
{
IList<string> errorMessages;
var isValidJson = IsValidJsonSchema(filterContext, requestData, out errorMessages);
if (!isValidJson)
{
var objectResult = new ObjectResult("Exception");
filterContext.Result = objectResult;
}
}
}
}
catch (Exception ex)
{
filterContext.Result = new BadRequestResult();
}
base.OnActionExecuting(filterContext);
}
//To validate the Json Schema with action request parameter schema
private bool IsValidJsonSchema(ActionExecutingContext filterContext, string requestData, out IList<string> errorMessages)
{
errorMessages = null;
// foreach (var postItem in filterContext.ActionArguments)
foreach (var postItem in filterContext.ActionDescriptor.Parameters)
{
Newtonsoft.Json.JsonConvert.DefaultSettings = (() =>
{
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter());
return settings;
});
Type objType = postItem.ParameterType;
JSchemaGenerator jSchemaGenerator = new JSchemaGenerator();
jSchemaGenerator.GenerationProviders.Add (new StringEnumGenerationProvider());
//jSchemaGenerator.ContractResolver = new ShouldSerializeContractResolver();
jSchemaGenerator.SchemaReferenceHandling = SchemaReferenceHandling.None;
var schemaJson = jSchemaGenerator.Generate(objType);
JSchema schema = JSchema.Parse(schemaJson.ToString().ToLower());
JObject jsonObject = JObject.Parse(requestData.ToLower());
bool isValid = jsonObject.IsValid(schema, out errorMessages);
if (!isValid)
return isValid;
}
return true;
}
//To validate the XML Schema with action request parameter schema
private bool IsValidXmlSchema(ActionExecutingContext filterContext, string requestData, out string errorMessages)
{
errorMessages = null;
foreach (var postItem in filterContext.ActionDescriptor.Parameters)
{
Type objType = postItem.ParameterType;
var schemas = new XmlSchemas();
var exporter = new XmlSchemaExporter(schemas);
var mapping = new XmlReflectionImporter().ImportTypeMapping(objType);
exporter.ExportTypeMapping(mapping);
var schemaWriter = new StringWriter();
foreach (XmlSchema schema in schemas)
{
schema.Write(schemaWriter);
}
var xsdMarkup = schemaWriter.ToString();
bool isValid = ValidateXmlSchema(requestData, xsdMarkup, out errorMessages);
if (!isValid)
return isValid;
}
return true;
}
private bool ValidateXmlSchema(string strXml, string xsdMarkup, out string errorMessages)
{
errorMessages = string.Empty;
try
{
string strErrorMessage = string.Empty;
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(xsdMarkup)));
XDocument xDocument = XDocument.Parse(strXml);
xDocument.Validate(schemas, (o, e) =>
{
strErrorMessage = e.Message;
});
errorMessages = strErrorMessage;
if (errorMessages != string.Empty)
return false;
}
catch (Exception ex)
{
errorMessages = ex.Message;
return false;
}
return true;
}
}
public class est
{
[XmlElement(IsNullable =true)] // Required property setting
public HeaderNode Header { get; set; }
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] // Optional property setting
[XmlElement(IsNullable = false)] // Optional property setting
public ImportNode Import { get; set; }
}
public class HeaderNode
{
public string Version { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public enumAppName AppName { get; set; }
public string AppVersion { get; set; }
public string Database { get; set; }
}
Comments
Post a Comment