0

I have a 3rd party API as shown in below image. enter image description here

I'm trying to call this API in ASP.Net MVC controller as below:

public ActionResult GetQuickCatalogueAsync(string category = "f97b9ec8-5e74-4f20-8582-471d067fc6c4")
        {
            using (var client = new HttpClient())
            {
                var data = JsonConvert.SerializeObject(new
                {
                    Content = new { categoryId = category },
                    Key = "test",
                    Name = "get-products"
                });
                StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
                
                var res = client.PostAsync(_baseUrl, content).Result.Content.ReadAsStringAsync().Result;
                var response = JsonConvert.DeserializeObject<Product>(res);

                return Content("");
            }
        }

The PostAsync is not getting Payload body (content) properly here.

Generated data object:

{"content":{"categoryId":"f97b9ec8-5e74-4f20-8582-471d067fc6c4"},"key":"test","name":"get-products"}

Expected:

{"Name":"get-products","Key":"test","Content":"{ \u0022categoryId\u0022:\u0022f97b9ec8-5e74-4f20-8582-471d067fc6c4\u0022}"}

And the Error on Post

{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-d1fb352d7eb19d4cbdb542bc7cee59fb-e62da6de34faee4b-00","errors":{"$.content":["The JSON value could not be converted to System.String. Path: $.content | LineNumber: 0 | BytePositionInLine: 12."]}}
Unknown Coder
  • 1,510
  • 2
  • 28
  • 56
  • 1
    You need to `await` the result of your [asynchronous](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/) call. – Jasen Dec 07 '21 at 04:50
  • @Jasen looks like something to do with content format. Content payload format is not proper for post method. – Unknown Coder Dec 07 '21 at 05:11
  • You should still `await` the result, regardless. – Tsahi Asher Dec 07 '21 at 08:43
  • The anonymous object in `Content` was serialized to JSON correctly. You want to encode it to unicode entities before you set it to `Content`. – Tsahi Asher Dec 07 '21 at 08:50

0 Answers0