c# - jquery ajax 调用 .NET Web api 返回错误

标签 c# jquery callback asp.net-web-api jsonp

我正在测试一个简单的 ApiController:

namespace SMOnline.Controllers
{
    public class DocumentosController : ApiController
    {
        Documentos[] docs = new Documentos[] 
        { 
            new Documentos { ID = 1, Tipo = 1, Designacao = "FC001"}, 
            new Documentos { ID = 2, Tipo = 1, Designacao = "FC002"}
        };

        public IEnumerable<Documentos> GetAll()
        {
            return docs;
        }
    }
}

在客户端,我从不同的域调用它

$.ajax({
    async: true,
    type: 'GET', //GET or POST or PUT or DELETE verb
    url: apiUrl + 'Documentos/', // Location of the service
    dataType: 'jsonp', //Expected data format from server
})
.done(function (data) {
    // On success, 'data' contains a list of documents.
    $.each(data, function (key, item) {
       alert(item.Designacao);
    })
})
.fail(function (jqxhr, textStatus, error) {
    alert(textStatus + " " + error);
});

我的问题是 JSONP 请求总是返回错误

parsererror Error: jQuery20301899278084596997_1380125445432 was not called

我一直在寻找,但仍然没有找到解决方案。

编辑: 我忘了提到,使用 fiddler 返回的值似乎正确的 header 是 200,内容是一个 JSON 数组。

最佳答案

看看WebApiContrib.Formatting.Jsonp正确处理您的 JSONP 调用。

在包管理器控制台上:

Install-Package WebApiContrib.Formatting.Jsonp

关于c# - jquery ajax 调用 .NET Web api 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19010059/

相关文章:

c# - 以 Datatable 作为 ItemSsource 的 WPF Datagrid 分组

c# - Uri.IsWellFormedUriString 用于相对 Hashbang url 兼容性

c# - select查询值临时存放在哪里,如何分别获取每个值

javascript - 在触发元素外单击时隐藏元素

javascript - 在 Meteor.js 中, stub 的数据库写入是否总是在 stub 完成后立即完成?

javascript - 直接将函数与匿名函数传递给 then Promise 回调

javascript - 具有回调数组的 JS 函数

c# - 如果测试方法失败,如何使构建失败?

Jquery Ajax JSONP 错误未触发

javascript - 使用 SheetJs 读取 Excel 文件 - Javascript