How to receive JSON data on WebAPI backend C#?

前端 未结 4 1267
独厮守ぢ
独厮守ぢ 2020-12-08 07:19

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,
    \"T         


        
相关标签:
4条回答
  • 2020-12-08 07:44

    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)
    {
    }
    
    0 讨论(0)
  • 2020-12-08 07:48

    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.

    0 讨论(0)
  • 2020-12-08 07:50

    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");
    
                    }
                });
            }
    
    0 讨论(0)
  • 2020-12-08 07:58

    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

    0 讨论(0)
提交回复
热议问题