REST service with ASP.NET MVC: Part 2

Share This

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.


Leave a Reply

Recent Revive AdServer (Formerly OpenX Source) Expandable Banners

Revive AdServer (Formerly OpenX Source)  Expandable Banners The following example demonstrates a 600px by 150px banner served by Revive AdServer (Formerly OpenX Source)  and expanded to 600px by 300px on rollover. The flash creative can be either uploaded to creatives directory directly (FTP) or just as an another Revive AdServer (Formerly OpenX Source)  banner (preferred). When uploading the SWF creative, you do not need to replace any hardcoded URLs or indicate a destination URL – that would be done in the HTML banner setup. Essentially, we are just using it as a storage container for our creative, all impressions and clicks will be … read more

 Twitter  LinkedIn  Google+  Skype RSS

Get in Touch

  • r Phone:
    (416) 877 2844 / (647) 258 4847
  • h Email:
    [email protected]
  • m Address:
    1454 Dundas St. East, Suite 124
    Mississauga, Ontario
    L4X1L4, Canada

Any Questions?

    Email

    Message