Consuming JSON/REST web services with .Net

I allways find consuming JSON/REST web services using .Net cumbersome (at least without 3rd part libraries). Not sure why, maybe I’m doing it all wrong.

Anyway, here’s a method I once created for calling a JSON/REST service using basic authentication, POST or GET, serialization of request body parameters and deserialization of the results into typed classes. I remember I was very happy when made it, so maybe you are here because you face simliar problems as I did at the time. It can be improved and adapted, but at least it’s something to copy/paste from.

/// <summary>
/// Call JSON/REST web service with basic authentication
/// </summary>
/// <typeparam name="T">The type to seserialize response to and return</typeparam>
/// <param name="uri">Uri of the web service method</param>
/// <param name="requestBodyObject">Object to serialize and pass to web service method</param>
/// <param name="method">HTTP method/verb, "POST" or "GET"</param>
/// <param name="username">Optional username if basic authentication is to be used</param>
/// <param name="password">Optional password if basic authentication password is used</param>
/// <returns></returns>
private T CallRestJsonService<T>(string uri, object requestBodyObject, string method = "POST", string username = "", string password = "")
{
	var javaScriptSerializer = new JavaScriptSerializer();
	javaScriptSerializer.MaxJsonLength = 104857600; //200 MB unicode
	var request = (HttpWebRequest)WebRequest.Create(uri);
	request.Method = method;
	request.Accept = "application/json";
	request.ContentType = "application/json; charset=utf-8";

	//Add basic authentication header if username is supplied
	if (!string.IsNullOrEmpty(username))
	{
		request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password)); ;
	}

	//Serialize request object as JSON and write to request body
	if (requestBodyObject != null)
	{
		var stringBuilder = new StringBuilder();
		javaScriptSerializer.Serialize(requestBodyObject, stringBuilder);
		var requestBody = stringBuilder.ToString();
		request.ContentLength = requestBody.Length;
		var streamWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
		streamWriter.Write(requestBody);
		streamWriter.Close();
	}

	var response = request.GetResponse();

	if (response == null)
	{
		return default(T);
	}

	//Read JSON response stream and deserialize
	var streamReader = new System.IO.StreamReader(response.GetResponseStream());
	var responseContent = streamReader.ReadToEnd().Trim();
	var jsonObject = javaScriptSerializer.Deserialize<T>(responseContent);
	return jsonObject;
}

Here’s how to use it:

First, define a class matching the json response to deserialize to. If the expected json response is:

{
    "MyProperty": 1,
    "AnotherProperty": "OK"
}

It can be serialized into this class:

public class MyJsonObject
{
	public int MyProperty { get; set; }
	public string AnotherProperty { get; set; }
}

Then if you are to pass parameters as json with the request body, if this json object is expected:

{
    "SomeProperty": false,
    "AnArray": []
}

You can create an anonymous object for this:

var requestObject = new { SomeProperty = false, AnArray = new object[] { } };

Then, make the call, GET/POST and optionally basic authentication;

var result = CallRestJsonService<MyJsonObject>("http://url/to/service/method", requestObject, "POST", "myusername", "mypassword");

Good luck, please leave any comment.

  • Rocky

    Your post really help me alot. Thanks for the post. I have one question: I am using email address and password in requestBodyObject. I want to use email address and password as cookie and want to pass into next web form. How should I retrieve cookies from url. Reply ASAP.

  • cornbeast

    Sorry, I don’t really understand your question. There are no cookies or forms involved here. I think whatever you’re trying to achieve has to be done somewhere else in your application…

  • http://plasticanow.com.br/ pagina

    I’m not sure exactly why but this website is loading incredibly
    slow for me. Is anyone else having this issue or is it
    a problem on my end? I’ll check back later on and see if the problem
    still exists.

  • cornbeast

    Indeed it is. It’s wordpress and I’m on a cheap web hotel. Maybe I’ll deal with this some day…

  • http://galaxys4ieftin.blogspot.com/ samsung galaxy s4 pret

    Wow that was strange. I just wrote an incredibly long
    comment but after I clicked submit my comment didn’t appear.
    Grrrr… well I’m not writing all that over again.
    Anyways, just wanted to say great blog!

  • http://theappguruz.com Bhavik Jani

    As per your blog we can send Unicode data through web request.

    Can you please add some more code how to retrieve this request on server?

    Because when we try to decode this request we cannot get unicode characters [get just some box box box sign].

    Thanks.

  • Tina

    I have to pass the data to java rest service. Response is in xml format but request is in JSON. I have to achieve this using .Net.

    Will this method of your work?

  • Rodrigo Loures

    Congratulations!! Your post is excelent and your code is clean.

    Thanks!

  • http://www.abamsoft.de/forum/member.php?action=profile&uid=40601 Max

    Yoour method of explaining all in this paragraph is genuinely
    fastidious, alll be capable of simply understand it, Thanks a lot.

  • http://sujil sujil

    Thank you so much