Thursday, November 14, 2013

HTTP Requests to Rest-WCF/Web API service from C# MVC Apllication

      This tutorial explains you about the how to make HTTP requests to Rest-WCF/Web API service from C# MVC Client Application. HTTP is designed to enable communication between client and server. It works as a request-response between client and server. HTTP request methods are GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE and CONNECT. We use most commonly  POST, GET, PUT and DELETE methods. These methods correspond  to create, read, update and delete (CRUD) operations.

HTTP Post Method:
The HTTP POST is most-often utilized for creation of new resources. It simply submits data into specified resource.
I have created UserDetails model.

public class UserDetails
    {

        public int UserId { get; set; }
        public string FirstName { get; set; }
       public string LastName { get; set; }
       public string Email{ get; set; }
       public string Password{ get; set; }
       public string Phone{ get; set; }
    }



CODE:

//POST
public ActionResult SignUp()
        {
           UserDetails model = new UserDetails();
           WebClient clientpost = new WebClient();
            clientpost.Headers["Content-type"] = "application/json";
            MemoryStream streampost = new MemoryStream();
         
            model .UserId = 0;
            model .FirstName = "Teja";
            model .LastName = "Prakash";
            model .Email= "info@tejaprakash.com";
            model .Password= "password";
            model.Phone="xxx-xxx-xxxx"      

            DataContractJsonSerializer serializerpost = new                                                                                             DataContractJsonSerializer(typeof(UserDetails ));
         
            serializerpost.WriteObject(streampost, model);

            byte[] datapost = clientpost.UploadData("http://localhost:60273/PrakashSampleService.svc/Signup",              "POST", streampost.ToArray());

            streampost = new MemoryStream(datapost);
            serializerpost = new DataContractJsonSerializer(typeof(string));
            string result = (string)serializerpost.ReadObject(streampost);

            return View();
        }



HTTP Get Method:
The HTTP GET method is used to retrieve (or read) a representation of a resource. HTTP response codes- 200(OK), 404(NOT FOUND), 400(BAD REQUEST).

CODE:
   //GET
public ActionResult GetUserDetails(int userid)
        {

           UserDetails model = new UserDetails();

            string formatted_uri = string.Format("http://localhost:60273/PrakashSampleService.svc/{0}", userid);

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(formatted_uri);
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            string json_response = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                json_response = sr.ReadToEnd();
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            model  = serializer.Deserialize<model >(json_response);


            return View(model);

        }

HTTP PUT Method:
HTTP PUT is most-often utilized for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.

CODE:
//PUT
public ActionResult UpdateProfile()
        {
           UserDetails model = new UserDetails();
       
            WebClient clientpost = new WebClient();
            clientpost.Headers["Content-type"] = "application/json";
            MemoryStream streampost = new MemoryStream();
       
            model .UserId = 1;
            model .FirstName = "Teja";
            model .LastName = "Prakash rao";
            model .Email= "info@tejaprakash.com";
            model .Password= "password";
            model.Phone="xxx-xxx-xxxx"  

            DataContractJsonSerializer serializerpost = new                                                                                            DataContractJsonSerializer(typeof(UserDetails ));

            serializerpost.WriteObject(streampost, model);

            byte[] datapost = clientpost.UploadData("http://localhost:60273/PrakashSampleService.svc/UpdateProfile",  "PUT",streampost.ToArray());

            streampost = new MemoryStream(datapost);
            serializerpost = new DataContractJsonSerializer(typeof(string));
            string result = (string)serializerpost.ReadObject(streampost);

            return View();
        }

HTTP Delete Method:
HTTP DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.

CODE:
//DELETE
public ActionResult DeleteUser(int userid)
        {
         
            WebClient clientpost = new WebClient();
            clientpost.Headers["Content-type"] = "application/json";
            MemoryStream streampost = new MemoryStream();
     
            DataContractJsonSerializer serializerpost = new  DataContractJsonSerializer(typeof(String));
            serializerpost.WriteObject(streampost, userid);

            byte[] datapost = clientpost.UploadData("http://localhost:60273/PrakashSampleService.svc/DeleteUser", "DELETE", streampost.ToArray());

            streampost = new MemoryStream(datapost);
            serializerpost = new DataContractJsonSerializer(typeof(string));
            string result = (string)serializerpost.ReadObject(streampost);

            return View();


        }


This process works fine for both REST WCF and WEB API services.
Enjoy.....!!!!!
Read More »