有谁知道JSONP.net 4.5 ASP.NET WEB API 是否支持开箱即用的返回?
我为早期版本或 .net 找到了很多“自己动手”,MVC但似乎没有特定于更高版本的任何内容。
我意识到这可能是因为它们的早期版本可以与 .net 4.5 堆栈一起使用,但我很好奇是否有人已经加入。
有谁知道JSONP.net 4.5 ASP.NET WEB API 是否支持开箱即用的返回?
我为早期版本或 .net 找到了很多“自己动手”,MVC但似乎没有特定于更高版本的任何内容。
我意识到这可能是因为它们的早期版本可以与 .net 4.5 堆栈一起使用,但我很好奇是否有人已经加入。
据我所知,您必须获得 jsonp 格式化程序。这是其中一种实现:
http://nuget.org/packages/WebApi.JsonP
更新
WebApiContrib 团队现在提供推荐的软件包:
https://www.nuget.org/packages/WebApiContrib.Formatting.Jsonp
在应用程序启动时将其添加到 Global.asax:
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter()));
这是我发现的第一篇文章,也是最有帮助的,但它仍然留下了一些问题,我发现一些答案存在一些问题,虽然由于所有答案,我能够使其工作,但我想添加什么我之所以知道是因为它在搜索返回中似乎很高。
我安装了https://www.nuget.org/packages/WebApiContrib.Formatting.Jsonp并且在我添加后能够让它工作
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter()));
到我的 Global.asax 上的应用程序 startas Alex Wheat 和 mbudnik 回答说,它导致 CORS 停止处理我的 API 的其他部分,这些部分已经全部实现。
我现在一切正常,并从包开发人员的 github 中找出了一些东西。
安装 nuget 包后,将以下内容添加到 Global.asax 文件中
GlobalConfiguration.Configuration.AddJsonpFormatter();
那么如果您使用下面的 Jquery 调用该服务,只需将 url 替换为您的 url,您就可以在控制台中看到结果。我还建议安装 Fiddler Web Debugger,因为它可以帮助您进行故障排除。
$.ajax({
url: 'http://jsfiddle.net/echo/jsonp/',
type: 'GET',
contentType: 'text/javascript',
crossDomain: true,
success: function(data) {
console.log(data);
},
error: function(jqXHR,status,error) {
console.log(error);
}
});
contentType : 'text/javascript'很重要。这就是告诉 web api 使用 Jsonp Formatter 的原因。
不要包含“jsonp”的数据类型 - 下面的示例
...type: 'GET',
dataType: 'jsonp',
crossDomain: true,...
这将导致 web api 使用 JsonMediaTypeFormatter,您将收到“jQuery randomfunctionstring was not called parsererror”错误。我从个人的反复试验中知道这一点。希望这对其他人有帮助。
I like this WebApiContrib.Formatting.Jsonp NuGet package
Add this formatter into Application_Start:
GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter()));
我还最终使用了 WebApiContrib.Formating.Jsonp NuGet 包,但如果没有回调参数,则保留了在不填充的情况下重新调整 Json 的能力。
所以只有 Jsonp IF 我提供的回调参数。
通过添加(来自 howTo)到 Global.asax.cs - Application_Start()
GlobalConfiguration.Configuration.AddJsonpFormatter();