Validate incoming request with XSD

Topics: Web Api
Aug 24, 2011 at 1:59 AM

I've been trying to validate incoming XML with schema with limited success. I've been using XmlFormatter.XmlReaderSettings.Schemas to include our xsd for validation in global.asax.

The problem is the XML validation error is not propagated. All the client get is the default html error messages "The server encountered an error processing the request. See server logs for more details."

Is there a recommended way to introduce xsd validation to the incoming request?

My global.asax looks like this.

protected void Application_Start(object sender, EventArgs e)
    var config = HttpHostConfiguration.Create();
    var formatter = config.Configuration.OperationHandlerFactory.Formatters.XmlFormatter;
    formatter.XmlReaderSettings.Schemas.Add(null, GetSchemaPath("MySchema.xsd"));
    formatter.XmlReaderSettings.ValidationType = System.Xml.ValidationType.Schema;
    formatter.XmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

    //RouteTable.Routes.MapServiceRoute ... ;

private static void ValidationCallBack(object sender, ValidationEventArgs e)
    Logger.Error(string.Format("XSD validation error on Line {0}, Position {1}", e.Exception.LineNumber, e.Exception.LinePosition), e.Exception);
    throw e.Exception;

Many thanks in advance.