31

How do I receive JSON data on my WebAPI backend in C#?

I have the following JSON sent from my JavaScript frontend.

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

I have this classes:

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; }
 }

And my WebAPI method:

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

I only get "null" as the result for my "PurchaseOrder order" object. Can the problem be that I ́m using [System.Web.Mvc.HttpPost]? I have also tried [System.Web.Http.HttpPost], but get the same result. // Martin

asked Jun 24, 2015 at 9:22
4
  • 2
    Do you set the Content-Type to application/json on the JavaScript request? Commented Jun 24, 2015 at 9:23
  • 1
    Can you include the full Javascript request? Commented Jun 24, 2015 at 9:27
  • build a javascript object named order with your data and use JSON.stringify while posting. Commented Jun 24, 2015 at 9:27
  • Unless you're using vNext, this is wrong System.Web.Mvc.HttpPost it should come from the Http namespace I believe not the Mvc one. Secondly this is something to do with your JavaScript. Commented Jun 24, 2015 at 9:32

4 Answers 4

21

The Content-Type of your request should be "application/json"

If you post your json in a body of the request than change a method signature to

[HttpPost]
public bool AddOrder([FromBody] PurchaseOrder order)
{
}
answered Jun 24, 2015 at 9:25

3 Comments

contentType in javascript.
[FromBody] might not be necessary.
@AmitKumarGhosh No, [FromBody] is mostly assuredly necessary. By default, a WebApiController instance looks in the URL for parameters. If you're using a JSON string and posting that, instead, it has to look in the request body.
6

Problem solved, it was the "application/json" that was missing. For other persons having the same problem, here is my function. I ́m using Knockout.js, hence the "self"-word.

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");
 }
 });
 }
answered Jun 24, 2015 at 9:40

1 Comment

var self = this is a common thing, just let's you know what this you are referring to as this can change when you are inside say error: function () {} for example.
3

Change your implementation to this.

[System.Web.Http.HttpPost]
public bool AddOrder([FromBody] PurchaseOrder order)
{
}

For more details - http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

answered Jun 24, 2015 at 9:36

2 Comments

for WebApi, you should use this attribute [System.Web.Http.HttpPost]
@SaveendraEkanayake Looks like you were typing up this response at the same time as Anton & just submitted it 11 mins after he did... But it's basically the same thing-at least you have a link. Missed the part about the Content-Type.. but it didn't help that the OP didn't post his JavaScript - if he had, I'm sure you would've caught that, though. :wink:
-4

Try using Newtonsoft.Json package from NuGet. They have functions to serialize and deserialize any string to Json. Also try using dynamic type variables. Helps for deserializing.

answered Jun 24, 2015 at 9:38

2 Comments

this is not an answar.
Not an answer either.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.