REST service with ASP.NET MVC: Part 2
This previous article I showed you how to use ASP.NET MVC controller as RESTful service.
Now it’s time to build small application that serves as http client that consumes JSON, produced by our service.
We’ll use WebRequest class from .NET Framework to send HTTP REQUESTS and JavaScriptSerializer class to build objects from JSON.
First, lets create simple HTTP client for our application:
1. Simple enum to keep HTTP methods organized.
public enum HttpMethod { Get, Post, Put, Delete } |
2. Following class represents HttpParameter. Is contains two field for parameter name and value and overrides ToString() to create valid key=value pair from object data:
public class HttpParameter { public HttpParameter(string name, string value) { Name = name; Value = value; } private string Name { get; set; } private string Value { get; set; } public override string ToString() { return string.Format("{0}={1}", Name, Value); } } |
3. As soon as we might have more than one parameter, we need to support http parameter list: following class is derived from List and used for storing HttpParameter objects and create query string: key1=value1&key2=value2.. etc.
public class HttpParameterList : List { public override string ToString() { if (Count == 0) return string.Empty; var requestString = new StringBuilder(); foreach (var parameter in this.Where(parameter => parameter != null)) requestString.AppendFormat("{0}&", parameter); requestString.Remove(requestString.Length - 1, 1); //remove last & return requestString.ToString(); } } |
Now we are ready to send http query via WebRequest:
private string ExecuteRequest(string uri, HttpMethod method, HttpParameterList parameters) { if (string.IsNullOrEmpty(uri)) throw new ArgumentException("Uri cannot be empty", "uri"); if (parameters == null) throw new ArgumentException("Parameters cannot be null", "parameters"); // id we are using GET method, parametter list should be part of url if (method == HttpMethod.Get) requestPath = string.Format("{0}?{1}", uri, parameters); var request = (HttpWebRequest)WebRequest.Create(requestPath); //determine which http method to use switch (method) { case HttpMethod.Get: request.Method = "GET"; break; case HttpMethod.Post: request.Method = "POST"; break; case HttpMethod.Put: request.Method = "PUT"; break; case HttpMethod.Delete: request.Method = "DELETE"; break; } request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; // if HTTP methis is POST, DELETE or PUT we need to put our parameter into the request body if (method != HttpMethod.Get) { using (var requestWriter = new StreamWriter(request.GetRequestStream())) { requestWriter.Write(parameters.ToString()); } } // only thing left is to read response! var httpResponse = (HttpWebResponse)request.GetResponse(); using (var responseReader = new StreamReader(httpResponse.GetResponseStream())) { return responseReader.ReadToEnd(); } } |
Okay, we can get JSON from service now, let’s add some code to send request and convert resulting JSON to object:
public IList<Employee> GetEmployees(string dept) { string result = ExecuteRequest( "Service/GetEmployees", HttpMethod.Get, new HttpParameterList { new HttpParameter("department", dept) } ); var employees= new JavaScriptSerializer().Deserialize<IList<Employee>>(result); return employees; } |
Done! Now we can send request, parse JSON and return result from our RESTful service.