Way
Post:
private void button1_Click(object sender, EventArgs e) { string ss= HttpPost("http://localhost:41558/api/Demo/PostXXX", "{Code:\"test089\",Name:\"test1\"}"); } public static string HttpPost(string url, string body) { // = new RemoteCertificateValidationCallback(CheckValidationResult); Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)(url); = "POST"; = "text/html, application/xhtml+xml, */*"; = "application/json"; byte[] buffer = (body); = ; ().Write(buffer, 0, ); HttpWebResponse response = (HttpWebResponse)(); using (StreamReader reader = new StreamReader((), Encoding.UTF8)) { return (); } }
Get:
private void button1_Click(object sender, EventArgs e) { string ss = HttpGet("http://localhost:41558/api/Demo/GetXXX?Name=Beijing"); } public static string HttpGet(string url) { // = new RemoteCertificateValidationCallback(CheckValidationResult); Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)(url); = "GET"; = "text/html, application/xhtml+xml, */*"; = "application/json"; HttpWebResponse response = (HttpWebResponse)(); using (StreamReader reader = new StreamReader((), Encoding.UTF8)) { return (); } }
Way
Post:
private async void button2_Click(object sender, EventArgs e) { HttpClient client = new HttpClient(); //Deliver Method is issued by HttpClient HttpResponseMessage response = await ("http://localhost:41558/api/Demo"+"/1"); if () ("success"); } private async void button3_Click(object sender, EventArgs e) { //Create a DataContractJsonSerializer that handles serialization DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People)); MemoryStream ms = new MemoryStream(); //Write the data to MemoryStream (ms, new People() { Id = 1, Name = "Hello ni" }); //Be sure to set Position here = 0; HttpContent content = new StreamContent(ms);//Convert MemoryStream to HttpContent = new ("application/json"); HttpClient client = new HttpClient(); // Issue Put Method by HttpClient HttpResponseMessage response = await ("http://localhost:41558/api/Demo"+ "/1", content); if () ("success"); }
Get:
using (WebClient client = new WebClient()) { ["Type"] = "GET"; ["Accept"] = "application/json"; = Encoding.UTF8; += (senderobj, es) => { var obj = ; }; ("http://localhost:41558/api/Demo"); }
This is the end of this article about the implementation of C# calling WebApi. For more related content about C# calling WebApi, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!