2015-06-24 16 views
24

Come posso ricevere dati JSON sul mio back-end WebAPI in C#?Come ricevere i dati JSON sul backend WebAPI C#?

Ho il seguente JSON inviato dal mio frontend JavaScript.

{ 
    "User_Id": 1, 
    "TotalPrice": 35, 
    "DeliveryAddress": "At my house", 
    "CartItems": [ 
     { 
      "Id": 1009, 
      "Name": "Superman juni 2014", 
      "Quantity": 1, 
      "Price": 35 
     } 
    ] 
} 

ho questo classi:

public class PurchaseOrder 
    {   
     public List<CartItem> CartItems { get; set; } 
     public string DeliveryAddress { get; set; } 
     public int TotalPrice { get; set; } 
     public int User_Id { get; set; } 
    } 
public class CartItem 
    { 
     public int Id { get; set; } 
     public string Name { get; set; } 
     public int Quantity { get; set; } 
     public int Price { get; set; } 
    } 

E il mio metodo WebAPI:

[System.Web.Mvc.HttpPost] 
     public bool AddOrder(PurchaseOrder order) 
     { 
      // Here I will do something 

      return true; 
     } 

ho solo "null" come il risultato per il mio oggetto "ordine PurchaseOrder". Il problema è che sto usando [System.Web.Mvc.HttpPost]? Ho anche provato [System.Web.Http.HttpPost], ma ottengo lo stesso risultato. // Martin

+1

Imposta Content-Type su 'application/json' sulla richiesta JavaScript? – Markus

+0

Puoi includere la richiesta Javascript completa? – DavidG

+0

crea un oggetto javascript denominato 'order' con i tuoi dati e usa' JSON.stringify' durante la pubblicazione. –

risposta

11

La Content-Type della richiesta dovrebbe essere "application/json"

Se pubblichi il tuo JSON in un corpo della richiesta di cambiare una firma metodo per

[HttpPost] 
public bool AddOrder([FromBody] PurchaseOrder order) 
{ 
} 
+0

'contentType' in javascript. –

+0

'[FromBody]' potrebbe non essere necessario. –

-4

Prova utilizzando il pacchetto Newtonsoft.Json da NuGet. Hanno funzioni per serializzare e deserializzare qualsiasi stringa su Json. Prova anche a utilizzare variabili di tipo dinamiche. Aiuta a deserializzare.

+5

questa non è una risposta. –

+0

Non una risposta neanche. –

5

Problema risolto, era "l'applicazione/json" che mancava. Per altre persone che hanno lo stesso problema, ecco la mia funzione. Sto usando Knockout.js, da cui la parola "self".

self.makePurchase = function() { 
      var tempUserId = self.orderUserId(); 
      var tempCartPrice = self.ShoppingCartPrice(); 
      var tempAddress = self.orderAddress(); 
      var tempCart = self.ShoppingCart(); 

      var orderSave = new PurchaseSave(tempUserId, tempCartPrice, tempAddress, tempCart); 
      var myData = ko.toJSON(orderSave); 
      console.log(myData); 

      $.ajax({ 
       type: "POST", 
       async: false, 
       url: '/Products/AddOrder', 
       contentType: "application/json", // Thank you Stackoverflow!!! 
       dataType: "json", 
       traditional: true, 
       data: myData, 
       error: function (xhr, textStatus, errorThrown) { 
        console.log(xhr.responseText); 
        console.log("Inside the error method"); 

       }, 
       success: function (data) { 
        console.log("Inside the success method"); 

       } 
      }); 
     } 
+0

'var self = this' è una cosa comune, basta sapere che cosa si sta riferendo a questo in quanto questo può cambiare quando si è all'interno di dire' error: function() {} 'per esempio. –

Problemi correlati