Json.net Schema IsValid slow

I have a web service that interacts with the client with JSON messages, the runtime itself is not aware of the data model, so I am using the json.net schema to validate messages from the client and within the service itself, however This leads to a lot of overhead with performance point of view.

Simplified code that still contains enough context to understand what I am doing.

public class Template
{
    /// <summary>
    /// Template known as
    /// </summary>
    public string Name { get; private set; }
    /// <summary>
    /// Razor Template
    /// </summary>
    public string RazorTemplate { get; private set; }
    /// <summary>
    /// Json Schema definition
    /// </summary>
    public string Schema { get; private set; }

    private JSchema _schema { get; set; }

    private JSchema JSchema
    {
        get
        {
            if (_schema == null)
                _schema = JShema.Parse(Schema);

            return _schema;
        }
    }

    private void Validate(JObject obj)
    {
        // Schema validation Error messages.
        IList<string> ValidationError;

        // Schema validation.
        if (!obj.IsValid(JSchema, out ValidationError))
        {
            throw new Exception(string.Join(",", ValidationError.ToArray()));
        }
    }


    public string RunTemplate(JObject jobj)
    {
        // Validate Json Object. 
        Validate(jobj);

        // Code here that access our RazorEngine cache, and add then run Razor Template, or directly run a cached Razor Template...

        return "Here we return string generated by RazorEngine to sender.";
    }
}

      

Let's say I'm running a simple "Hello @ Model.Name!" a template that checks that the json has a Name string, this will be 15-20 times slower than if I fully commented out the check.

Are there better ways to use IsValid in a Json.Net schema?

+3


source to share


1 answer


Make sure you update to the latest version of Json.NET Schema available on NuGet, performance was slow when checking some schemas with older versions.



There is also documentation on the Json.NET Schema website for performance best practices .

+1


source







All Articles