0

On the browser, I could get data like this.(JSON format) enter image description here

I want to perform HTTP requests and get data on WinForm. How can I do to make it like the below picture?

enter image description here

I have referred to some relevant information. But I am confused how to start (like I should write code in Form1.cs or add new class, should I create model...)

How to make HTTP POST web request

How to return async HttpClient responses back to WinForm?

Can I use HttpClient Method? Thanks for answer and suggestion.


(New edit)

https://www.youtube.com/watch?v=PwH5sc-Q_Xk

I also learned from this video, But I got error message.

No MediaTypeFormatter is available to read an object of type 'IEnumerable`1' from content with media type 'text/html'.

My code

Form1.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Net.Http;
using System.Net.Http.Formatting;

namespace _123
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            HttpClient clint = new HttpClient();
            clint.BaseAddress = new Uri("http://localhost:8888/");
            HttpResponseMessage response = clint.GetAsync("PersonList").Result;

            var emp = response.Content.ReadAsAsync<IEnumerable<ImgList>>().Result;
            dataGridView1.DataSource = emp;
        }
    }
}

ImgList.cs (Is this Model?)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace _123
{
    class ImgList
    {
        public int id { get; set; }
        public string name { get; set; }
        public int age { get; set; }
    }
}

enter image description here

enter image description here

FJF
  • 125
  • 1
  • 2
  • 11
  • 2
    Create a class. Populate it with data. Serialize class/collection – Ňɏssa Pøngjǣrdenlarp Dec 03 '18 at 04:18
  • 2
    Did you try any of the approaches you found online? – Chetan Dec 03 '18 at 04:19
  • 1
    Exactly what @ChetanRanpariya said... first try those approaches you've found, formulate a more specific question and then we'll be able to help – Leo Dec 03 '18 at 04:20
  • Check the answer that I have posted, it has explicit assignment of the Media formatter `application\json` in the client request header, also you shall explicitly de-serialize the Result string received as Json, which I have shown in the code – Mrinal Kamboj Dec 03 '18 at 05:55
  • For an Async call you shall mark even as `async` and use `await clint.GetAsync`, currently you would be receiving out put as `Task` instead of `HttpResponseMessage`, since you are not awaiting, though you can use `response.Result.Content`, but that's not a suggested practice for an async call – Mrinal Kamboj Dec 03 '18 at 05:58

2 Answers2

2

On the browser, I could get data like this.(JSON format)

This is means you are making an HttpGet call with no parameters as I can see from the Url and in any case there's no HttpBody. For any other call like HttpPost, you have to use a tool like Postman, Fiddler

Following is the simple code to make a Http Get call using C#:

// Create HttpClient
var client = new HttpClient { BaseAddress = new Uri("http://localhost:8888/") };

// Assign default header (Json Serialization)
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ApiConstant.JsonHeader));    

// Make an API call and receive HttpResponseMessage
var responseMessage = await client.GetAsync("PersonList", HttpCompletionOption.ResponseContentRead);

// Convert the HttpResponseMessage to string
var resultArray = await result.Content.ReadAsStringAsync();

// Deserialize the Json string into type using JsonConvert
var personList = JsonConvert.DeserializeObject<List<Person>>(resultArray);

How it works

  • HttpClient is object which encompass the api service address
  • We ensure that assigned header is Json type for serialization / communication
  • Make an Async Http Get Call
  • HttpResponseMessage is used to extract string, which is de-serialized into List<Person> using NewtonSoft Json

Please note Async call means encompassing method shall be Async

Expected Schema for the Person class to fill the List<Person> using de-serialization:

public class Person
{
  public int id {get;set;}
  public string Name {get;set;}
  public int age {get;set;}
}

Where to call the code - Winform / Add new class

Standard mechanism would be to create a generic helper library / class, from which all the API calls are done, results are fetched, winform shall just do the data binding, not have the processing code

Mrinal Kamboj
  • 11,300
  • 5
  • 40
  • 74
  • Thank you for your answer. As you say, `Standard mechanism would be to create a generic helper library / class, from which all the API calls are done, results are fetched, winform shall just do the data binding, not have the processing code.` And I am still confused where to write the **Http Get call** code, not writing in Form1.cs but add a new class ( which different from Person.cs)? How to call it to Form1.cs and show the data? Sorry,if I ask a strange question I am new in C#. – FJF Dec 03 '18 at 07:59
  • You need some practice with C# to understand the details, in short when you create a helper class, it can be invoked from the Winform to fetch the details asynchronously. You just need to create an object and call, this helps in code separation and calling the rest api in a clean manner – Mrinal Kamboj Dec 03 '18 at 19:17
  • client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(ApiConstant.JasonHeader)); generates an error: The name 'apiConstent' does not exist in the current context – Saffa Seraj May 02 '21 at 19:26
  • @SaffaSeraj that's just a string constant value, which you can check what value does `MediaTypeWithQualityHeaderValue` takes and replace in the code – Mrinal Kamboj May 03 '21 at 10:21
-2

Use Json and Serialize your data with the model. And Assign Form Fields with the model.

Mdyahiya
  • 167
  • 3
  • 15