Creating REST Service using ASP.NET Web API with post,get methods

Creating REST Service using ASP.NET Web API with post,get methods

Introduction :


What is rest ?REST  stands for Representational State Transfer. It is a software design pattern introduced as an alternative to SOAP-based data exchange and is a way for programs to talk over the web.

RESTful services uses HTTP (Hyper Text Transfer Protocol) to communicate. REST system interface with external systems as web resources identified by URIs (Uniform Resource Identifiers). 

Http Verbs :

GET [HttpGet] :

 this verb is used to retrieve the data or information. It does not have any other effect except getting data.

Post [HttpPost] :

This verb is used to generate or create the resource. For example, If we have to add some information to the database then we must define the method as a POST method. The most common form to submit the data into the POST method is to pass the data into any entity object.

 Put [HttpPut]:

This verb is used to update the existing resource. For example, If we have to update some information to the database then we can define the method as a PUT method. We can send the data in the form of object as well as in a parameter too.

Delete [HttpDelete] :

This verb is used to delete the existing resource. For example, If we have to delete some information to the database then we can define the method as a DELETE method. We can send the data in the form of object as well as in a parameter too.

Step 1  Create ASP.NET  Web API Project 

step 2 : Create empty apiController.cs

Step 3 : In WebApiConfig.cs add  "SupportedMediaTypes" like Json or xml 

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Formatters.JsonFormatter.
           SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

            config.Routes.MapHttpRoute(
               name: "WithActionApi",
                routeTemplate: "api/{controller}/{action}"
                );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

Step 4 : Add class Home.cs for data access

    public class Home
    {
        public int EmpID { get; set; }
        public string Name { get; set; }
        public string Phone { get; set; }
        public string City { get; set; }

    }

Step 5 : Create HttpPost method  "AddEmployee" In RestApi controller called  "apiController"  and add Below code.


        [HttpPost]
        public string AddEmployee([FromBody] Home h)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("SP_InsertEmployee", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@EmpID", SqlDbType.Int);
            cmd.Parameters.Add("@Name", SqlDbType.VarChar);
            cmd.Parameters.Add("@Phone", SqlDbType.VarChar);
            cmd.Parameters.Add("@City", SqlDbType.VarChar);

            cmd.Parameters["@EmpID"].Value = 0;
            cmd.Parameters["@Name"].Value = h.Name;
            cmd.Parameters["@Phone"].Value = h.Phone;
            cmd.Parameters["@City"].Value = h.City;
            cmd.ExecuteNonQuery();
            con.Close();
            cmd.Dispose();
                   return "submited succesfully";

        }

Step 6 : Create ActionResult method InsertEmployee() and Post data using localhost RestApi url : http://localapitest.com/api/ApiCon/  

 [HttpPost]
        public ActionResult InsertEmployee(string Name, string City, string Phone)
        {
            string baseurl ="http://localapitest.com/api/ApiCon/";
            string url = "AddEmployee";
            string responseMessage = "";
            Home hm = new Home();
            hm.Name = Name;
            hm.City = City;
            hm.Phone = Phone;


            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseurl + url);
            request.Method = "POST";
            request.ContentType = "application/json";
            string jsonOrder = JsonConvert.SerializeObject(hm);
            var data = Encoding.UTF8.GetBytes(jsonOrder);
            request.ContentLength = data.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            WebResponse response = request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            if (((HttpWebResponse)response).StatusDescription == "OK")
            {
                using (var stream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(stream);
                    responseMessage = reader.ReadToEnd();

                }
            } 
            return View();
        }

Step 7 : Now add view for above ActionResult Method InsertEmployee.cshtml



@model MvcCallRestApi.Models.Home


<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script>
    function Data() {

        var Name = $("#Name").val();
        var City = $("#City").val();
        var Phone = $("#Phone").val();

        $.ajax({
            url: '@Url.Action("InsertEmployee")',
            data: { Name: Name, City: City, Phone: Phone },
            type: 'POST',
            dataType: 'json',
            success: function (result) {             

            }
        });
    }

</script>

<h2>InsertEmployee</h2>

    <fieldset>
        <legend>Home</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Phone)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Phone)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.City)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.City)
        </div>

        <p>
            <input type="submit" value="Create" onclick="Data();" />
        </p>
    </fieldset>


<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


RestApi



Step  8 :  Now you can implement get method in RestApi and retrieve data from database.

 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);   

        public List<Home> Select_data()
        {
            List<Home> D = new List<Home>();
            try
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("sp_getEmployee", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Home da = new Home();
                    da.EmpID = Convert.ToInt32(dr["EmpID"].ToString());
                    da.Name = dr["Name"].ToString();
                    da.Phone = dr["Phone"].ToString();
                    da.City = dr["City"].ToString();
                 
                    D.Add(da);
                }
                dr.Dispose();
                con.Close();
            }
            catch (Exception)
            {
            }

            return D;
        }

        [HttpGet]     // This method get data from database and return to client
        public List<Home> GetEmployee()   
        {
            return Select_data();
        }

Step 9 :Now call this RestApi method "GetEmployee" from client side as below code.

     [HttpGet]
        public ActionResult getEmployedata()
        {
            List<Home> hm = new List<Home>();
            string data = "";
            string url = "http://localapitest.com//api/ApiCon/GetEmployee";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "text/html";
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                data = reader.ReadToEnd();
                hm = JsonConvert.DeserializeObject<List<Home>>(data); 
            }
            return View(hm);
        }


Rest Api Get method


Step 10 : Now add view to display data getemployedata.cshtml


@model IEnumerable<MvcCallRestApi.Models.Home>

@{
    ViewBag.Title = "getEmployedata";
}

<h2>getEmployedata</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.EmpID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Phone)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.City)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.EmpID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Phone)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.City)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>


Resp Api with post ,get,put method



Previous
Next Post »