2012-09-25 54 views
1

我試圖創建一個Web API,它可以接受對象作爲參數傳遞對象MVC 4的Web API ...我開始貼在下面的簡單的例子,但我得到一個內部服務器錯誤使用jQuery AJAX

我的AJAX:

var order = { 
    "id": 1, 
    "carrier": "works", 
    "created_at": "works", 
    "description": "works", 
    "etd": "works", 
    "invoice_id": 12, 
    "origin_id": 13, 
    "po_number": "101", 
    "shipped_on": "works", 
    "status": "works", 
    "updated_at": "works" 
}; 

$.ajax({ 
    url: "http://localhost:3495/api/NTOrder/", 
    type: "GET", 
    data: { inputOrder: order }, 
    beforeSend: function(xhr){ 
     xhr.setRequestHeader('username', 'user4'); 
     xhr.setRequestHeader('password', 'secret'); 
    }, 
    success: function(data) { 
     alert('Success!' + JSON.stringify(data)); $('.result').html(data); 
    } 
}); 

在Chrome中,它給了我嘗試訪問該網址時,500內部服務器錯誤:

http://localhost:3495/api/NTOrder/?inputOrder%5Bid%5D=1&inputOrder%5Bcarrier%5D=works&inputOrder%5Bcreated_at%5D=works&inputOrder%5Bdescription%5D=works&inputOrder%5Betd%5D=works&inputOrder%5Binvoice_id%5D=12&inputOrder%5Borigin_id%5D=13&inputOrder%5Bpo_number%5D=101&inputOrder%5Bshipped_on%5D=works&inputOrder%5Bstatus%5D=works&inputOrder%5Bupdated_at%5D=works 

它是否正確創建URL字符串?

我在MVC端代碼很簡單:

public IEnumerable<NTOrder> GetOrders(NTOrder inputOrder) 
{ 
    List<NTOrder> NTOrderList = new List<NTOrder>(); 
    NTOrderList.Add(inputOrder); 
    return NTOrderList; 
} 

類NTOrder是相當簡單的,只包含原AJAX使用的屬性。

回答

3

如果你可以切換到POST而不是GET,你可以這樣做。你可能會有更好的運氣。

$.ajax({ 
    url: "http://localhost:3495/api/NTOrder/", 
    type: "POST", 
    data: JSON.stringify({ inputOrder: order }), 
    dataType: "json", 
    beforeSend: function(xhr){ 
     xhr.setRequestHeader('username', 'user4'); 
     xhr.setRequestHeader('password', 'secret'); 
    }, 
    success: function(data) { 
     alert('Success!' + JSON.stringify(data)); $('.result').html(data); 
    } 
});