Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling invalid JSONP requests in Web API

I am using WebApiContrib.Formatting.Jsonp within a Web API 2 service, plus Swagger for API documentation and testing.

When I trigger any JSONP method through Swagger, my service crashes in file JsonpMediaTypeFormatter.cs on the following line:

throw new InvalidOperationException(Properties.Resources.NoCallback);
// NoCallback = The name 'NoCallback' does not exist in the current context

For one thing, I don't understand why Swagger doesn't allow specifying a callback name for JSONP requests. But more importantly, I don't want the service to crash because of it.

Questions:

  • How can we handle such errors on the service side?
  • Is there a way to make Swagger send JSONP requests properly? (like pre-defining a callback name for all JSONP requests?)
like image 523
vitaly-t Avatar asked Aug 12 '16 14:08

vitaly-t


1 Answers

PM> Install-Package Newtonsoft.Json.Schema

Or you can down load the source at https://github.com/JamesNK/Newtonsoft.Json.Schema/releases

JSchema schema = JSchema.Parse(request.Schema);
JToken json = JToken.Parse(request.Json);

// validate json
IList<ValidationError> errors;
bool valid = json.IsValid(schema, out errors);

// return error messages and line info to the browser
return new ValidateResponse
{
    Valid = valid,
    Errors = errors
};
like image 59
Balan Avatar answered Sep 27 '22 22:09

Balan