Recently I've been working on integration point that accepts JSON object as a request payload over HTTP. This sounds really trivial when using ASP.NET Web API. Still there was an additional requirement to validate request against JSON schema that is distributed to customers as specification.
Since it was my first experience with Web API I started with a research and found this great article "How Web API does Parameter Binding". Here are 2 important notes from the article:
- in my case using media type formatter seems to be better option than model binder
- Web API request body can be read only once
As for formatter Web API comes with JsonMediaTypeFormatter that can be configured to use Json .NET for serialization. This is pretty cool since Json .NET supports schema validation. Unfortunately with current JsonMediaTypeFormatter implementation it is not possible to plug in validation code easily, but for now there is a workaround solution to decorate original formatter:
ValidationAwareJsonMediaTypeFormatter should be configured with typeSchemaResolver callback that should provide JsonSchema for payload type that is being deserialized. To hack the body stream that is already read by original formatter we seek the stream to the beginning and path it to validation reader that reports all found errors to standard IFormatterLogger. This approach requires body to be read twice and will work only for body streams that support seeking. Still it suites our needs and is better than implementing json formatter from scratch. If the following patch is applied things should become easier and less hacky.
Now we need to configure application to use new formatter:
I do not describe details about IJsonSchemaProvider because it does not depend on Web API and can use any implementation (the easiest probably is a hardcoded dictionary).
That is basically all - if your provider returns json schema for specific type, than request will be validated against it.
No comments:
Post a Comment