Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to call a JSON WebService from a .NET Console

I am hosting a web service in ASP.Net MVC3 which returns a Json string. What is the best way to call the webservice from a c# console application, and parse the return into a .NET object?

Should I reference MVC3 in my console app?

Json.Net has some nice methods for serializing and deserializing .NET objects, but I don't see that it has ways for POSTing and GETing values from a webservice.

Or should I just create my own helper method for POSTing and GETing to the web service? How would I serialize my .net object to key value pairs?

like image 918
BrokeMyLegBiking Avatar asked Nov 25 '11 14:11

BrokeMyLegBiking


People also ask

How do I call a webservice in C#?

In the Project Type pane, select a Visual C# application. In the Templates pane, select a Windows Forms Application. Enter a project name such as CallingServiceExample , and browse to a storage location. In the Solution Explorer, right-click the project name and click Add Service Reference.

How do I post JSON data to API using C#?

To post JSON to a REST API endpoint using C#/. NET, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the C#/. NET POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

Does JSON work with C#?

Today, JSON is one of the main formats for representing complex structures and data exchange. Therefore, all major programming languages have built-in support for working with it. C# is no exception.


1 Answers

I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:

// Returns JSON string string GET(string url)  {     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);     try {         WebResponse response = request.GetResponse();         using (Stream responseStream = response.GetResponseStream()) {             StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);             return reader.ReadToEnd();         }     }     catch (WebException ex) {         WebResponse errorResponse = ex.Response;         using (Stream responseStream = errorResponse.GetResponseStream())         {             StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));             String errorText = reader.ReadToEnd();             // log errorText         }         throw;     } } 

I then use JSON.Net to dynamically parse the string. Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/

POST looks like this:

// POST a JSON string void POST(string url, string jsonContent)  {     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);     request.Method = "POST";      System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();     Byte[] byteArray = encoding.GetBytes(jsonContent);      request.ContentLength = byteArray.Length;     request.ContentType = @"application/json";      using (Stream dataStream = request.GetRequestStream()) {         dataStream.Write(byteArray, 0, byteArray.Length);     }     long length = 0;     try {         using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {             length = response.ContentLength;         }     }     catch (WebException ex) {         // Log exception and throw as for GET example above     } } 

I use code like this in automated tests of our web service.

like image 115
GarethOwen Avatar answered Oct 13 '22 00:10

GarethOwen