Search code examples
c#jsonhttpclienthttpcontent

POST data using HttpClient


I'm trying to POST a data to web using HttpClient but i can't succeed.

Here is my JSON web api

{
    "Categories":[
        {
            "CategoryID":1,
            "Category":"Category 1"
        },
        {
            "CategoryID":2,
            "Category":"Category 2"
        }
    ]
}

i'am sending categories data to web my web developer send me above json to send a data from winform to web

Here is my code

IEnumerable<KeyValuePair<string, string>> paramt = new List<KeyValuePair<string, string>>()
                {
                    new KeyValuePair<string,string>("CategoryID","1"),
                    new KeyValuePair<string,string>("Category","Pizza")
                };
                HttpContent q = new FormUrlEncodedContent(paramt);
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.BaseAddress = new Uri(url);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", api);
                    HttpResponseMessage response = client.PostAsync("api/categories", q).Result;
 }

sorry for my english moderator please update my question


Solution

  • Thanks @John with the help of yours i did this

    public class CategoryItem
            {
                public int CategoryID { get; set; }
                public string Category { get; set; }
            }
    
            public class CategoriesRoot
            {
                public IList<CategoryItem> Categories { get; set; }
            }
    
             var tmp = new CategoriesRoot
                    {
                        Categories = new List<CategoryItem> {
                        new CategoryItem { CategoryID = 1, Category = "Pizza" }
                    }
                    };
    
                    using (HttpClient client = new HttpClient())
                    {
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.BaseAddress = new Uri(url);
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", api);
                        HttpResponseMessage response = client.PostAsJsonAsync("api/categories", tmp).Result;
                        }