Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

388
Visualizações
How to receive JSON data on WebAPI backend C#?

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

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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)
{
}
over 4 years ago · Santiago Trujillo Relatório

0

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");

                }
            });
        }
over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda