在Web API中处理无效的JSONP请求

时间:2016-08-12 14:23:06

标签: c# asp.net asp.net-web-api swagger web-api-contrib

我在Web API 2服务中使用WebApiContrib.Formatting.Jsonp,并在API文档和测试中使用Swagger

当我通过Swagger触发任何JSONP方法时,我的服务在以下行的文件JsonpMediaTypeFormatter.cs中崩溃:

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

首先,我不明白为什么Swagger不允许为JSONP请求指定回调名称。但更重要的是,我不希望服务崩溃,因为它。

问题:

  • 我们如何在服务方面处理此类错误?
  • 有没有办法让Swagger正确发送JSONP请求? (比如为所有JSONP请求预先定义一个回调名称?)

1 个答案:

答案 0 :(得分:1)

PM> Install-Package Newtonsoft.Json.Schema

或者您可以在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
};