Отправка списка объектов в метод web api с использованием C # с обеих сторон — JSON передается как NULL.?

#json #asp.net-mvc #webapi

#json #asp.net-mvc #webapi

Вопрос:

У меня возникли проблемы с получением JSON для перехода к методу API с помощью приведенного ниже кода. Я пытался отправить его как строку JSON, и как список, и как строку содержимого, но все 3 дают мне null JSON на стороне API.

Вот JSON списка

 [
{"Id":19,"ScanMode":"SHRINK_SCAN","itemcode":"01600027746rn","itemname":"BISQUICK GLUTEN FREE","FriendlyDisplayName":"UPC/PLU: 01600027746rn  Prod Desc: BISQUICK GLUTEN FREE","Quantity":1,"QuantityDisplay":"Quantity: 1","StoreNumber":"71","DateTimeOfScan":"2020-10-05T22:51:55.392313","UserId":"2aebb04e","UserName":"brian","departmentid":"8","departmentname":"Grocery","vendorid":"","VendorName":"Not Available","ReasonCode":"","Weight":0.0,"retailprice":2.99,"isweight":false,"TotalKLAmount":0.0},
{"Id":20,"ScanMode":"SHRINK_SCAN","itemcode":"01600027746rn","itemname":"BISQUICK GLUTEN FREE","FriendlyDisplayName":"UPC/PLU: 01600027746rn  Prod Desc: BISQUICK GLUTEN FREE","Quantity":1,"QuantityDisplay":"Quantity: 1","StoreNumber":"71","DateTimeOfScan":"2020-10-05T22:52:33.752041","UserId":"2aebb04e","UserName":"brian","departmentid":"8","departmentname":"Grocery","vendorid":"","VendorName":"Not Available","ReasonCode":"","Weight":0.0,"retailprice":2.99,"isweight":false,"TotalKLAmount":0.0},
{"Id":21,"ScanMode":"SHRINK_SCAN","itemcode":"01600027746rn","itemname":"BISQUICK GLUTEN FREE","FriendlyDisplayName":"UPC/PLU: 01600027746rn  Prod Desc: BISQUICK GLUTEN FREE","Quantity":1,"QuantityDisplay":"Quantity: 1","StoreNumber":"71","DateTimeOfScan":"2020-10-05T22:52:08.589202","UserId":"2aebb04e","UserName":"brian","departmentid":"8","departmentname":"Grocery","vendorid":"","VendorName":"Not Available","ReasonCode":"","Weight":0.0,"retailprice":2.99,"isweight":false,"TotalKLAmount":0.0}
]
  

Вот код из приложения для Android, пытающегося отправить список отправки JSON в API:

     public async Task<string> SubmitKnownLossItemsAsync(List<Item> items, int companyId)
    {
        string token = Constants.PrivateToken;
        string returnVal = string.Empty;

        try
        {
            //i tried both these approaches sending as jsonstring and sending as StringContent
            string jsonItems = JsonConvert.SerializeObject(items);
            StringContent content = new StringContent(jsonItems, Encoding.UTF8, "application/json");

            string url = string.Format(Constants.POSTKNOWNLOSS_ResultURL, companyId, token);

            Uri uri = new Uri(url);

            HttpResponseMessage response = null;

            //none of these 3 trys worked...
            //response = await client.PostAsJsonAsync(uri, content);
            //response = await client.PostAsJsonAsync(uri, jsonItems);
            response = await client.PostAsJsonAsync<List<Item>>(uri, items);


            if (response.IsSuccessStatusCode)
            {
                returnVal = "Success";
            }

        }
        catch (Exception ex)
        {
            //add logging to log the exception
            returnVal = string.Format("ERROR {0}", ex.Message);
            returnVal = "Failure";
        }

        return returnVal;
    }
  

КОД API:

 [AcceptVerbs("POST")]
    public IHttpActionResult PostShrinkItems(int companyId, string APIToken, [FromBody] string jsonItems)
    {
        
        SQLMethods sql = new SQLMethods();

        string returnValue = string.Empty;

        bool response = sql.ValidateAPIToken(APIToken);
        
        if (!response)
        {
            throw new Exception("Unauthorized Request - invalid APIToken provided.");

        }
        else
        {
            returnValue = sql.InsertShrinkData(jsonItems, companyId);
        }

        return Ok(returnValue);
    }
  

Ответ №1:

Я разобрался с проблемой и теперь она работает….

Сигнатура метода webapi была неправильной:

Вот какой должна быть подпись, чтобы заставить ее работать — сейчас она отлично работает.

[AcceptVerbs(«POST»)] public IHttpActionResult PostShrinkItems(int CompanyID, string APIToken, [From body]Список jsonItems)

—список отсутствовал после [FromBody] [FromBody]List jsonItems

Спасибо, Брайан