Search This Blog

Wednesday 31 January 2018

Create Simple WebApi Step By Step in C Sharp

Step 1:- Open Visual Studio 2015 => Goto File Menu => New => Project...

Step 2:- In the Installed Templates list, select Visual C# => Web

Step 3:- Select ASP.Net Web Application from the Web list => Type WebApiDemo in the Name box and click OK

Step 4:- Select Empty template from ASP.NET Templates List and Checked Web API check box under Add folders and core references for:



Step 5:- Right-click Models folder in Solution Explorer => Add => Click New Items...

Step 6:- In the Installed Templates list, select Visual C# = > Code

Step 7:- Select Class from the Code list => Type Product in the Name box and Click Add



Step 8:- Copy Past following Product properties to Product class

public int ProductId { get; set; }
public string ProductName { get; set; }
public string ProductCode { get; set; }
public int ProductQty { get; set; }
public decimal ProductWeight { get; set; }
public string ProductDesc { get; set; }



Step 9:- Right-click Controllers folder in Solution Explorer => Add => Click Controllers...

Step 8:- Select Web API 2 Controller – Empty from the controller list = > Click Add



Step 9:- Type ProductController in the Controller name box and Click Add

Step 10:- Replace Product Controller code with following code

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebApiDemo.Models;

namespace WebApiDemo.Controllers
{
    public class ProductController : ApiController
    {
        Product[] products = new Product[]
        {
            new Product { ProductId = 1, ProductName = "Parle G", ProductCode = "P001", ProductQty = 12, ProductWeight=1068,ProductDesc="Parle G" },
            new Product { ProductId = 2, ProductName = "Krackjack", ProductCode = "P002", ProductQty = 12, ProductWeight=900,ProductDesc="Krackjack" },
            new Product { ProductId = 3, ProductName = "Bourbon", ProductCode = "P003", ProductQty = 12, ProductWeight=1200,ProductDesc="Bourbon" },
            new Product { ProductId = 4, ProductName = "Marie Gold", ProductCode = "P004", ProductQty = 12, ProductWeight=1020,ProductDesc="Marie Gold" },
            new Product { ProductId = 5, ProductName = "50-50", ProductCode = "P005", ProductQty = 12, ProductWeight=960,ProductDesc="50-50" }
        };

        // GetAllProducts
        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        // GetProductByProductId
        public IHttpActionResult GetProductByProductId(int prodId)
        {
            Product p = products.FirstOrDefault(m => m.ProductId == prodId);
            if (p == null)
            {
                return NotFound();
            }
            return Ok(p);
        }
    }
}



Web API Created successfully

Run Project

If following error displayed, no issue.



Type api/product in URI to get all products details list.



Type api/product/?prodId=1 in URI to get specific product details.




Use the Google Chrome Browser to view result.

Note:-
If HttpVerbs not specify to action / method, the default behavior of an action / method is HttpGet.

Calling / Consuming the Web API


Step 1:- In Solution Explorer, right-click the project => Add => New Item...



Step 2:- In the Installed Templates list, select Visual C# => Web

Step 3:- Select HTML Page from the Web list => Type TestWebApiDemo in the Name box and click Add



Step 4:- Copy Past following code in TestWebApiDemo HTML Page

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            var row = "";
            var uri = 'api/product';

            //$.getJSON(uri)
            //    .done(function (data) {
            //        $.each(data, function (key, item) {
            //            row += formatItem(item);
            //        });
            //        $("#product tbody").append(row);
            //    }).fail(function (jqXHR, textStatus, err) {
            //        alert(err);
            //    });

            //$("#Search").click(function () {
            //    var prodId = $('#prodId').val();

            //    if (prodId === "" || isNaN(prodId)) {
            //        alert("Enter valid ProductId");
            //    }
            //    else {
            //        $.getJSON(uri + '/?prodId=' + prodId)
            //        .done(function (data) {
            //            $("#product tbody tr").remove();
            //            $("#product tbody").append(formatItem(data));
            //        })
            //        .fail(function (jqXHR, textStatus, err) {
            //            alert(err);
            //        });
            //    }
            //});

            $.ajax({
                type: "GET",
                url: uri,
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (key, item) {
                        row += formatItem(item);
                    });
                    $("#product tbody").append(row);
                },
                fail: function (jqXHR, textStatus, err) {
                    alert(err);
                }
            });

            $("#Search").click(function () {
                var prodId = $('#prodId').val();

                if (prodId === "" || isNaN(prodId)) {
                    alert("Enter valid ProductId");
                }
                else {
                    $.ajax({
                        type: "GET",
                        url: uri,
                        data: { prodId: prodId },
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            $.each(data, function (key, item) {
                                row += formatItem(item);
                            });
                            $("#product tbody tr").remove();
                            $("#product tbody").append(formatItem(data));
                        },
                        fail: function (jqXHR, textStatus, err) {
                            alert(err);
                        }
                    });
                }
            });

            function formatItem(item) {
                var row = "<tr>";
                row += "<td>" + item.ProductId + "</td>";
                row += "<td>" + item.ProductName + "</td>";
                row += "<td>" + item.ProductCode + "</td>";
                row += "<td>" + item.ProductQty + "</td>";
                row += "<td>" + item.ProductWeight + "</td>";
                row += "<td>" + item.ProductDesc + "</td>";
                row += "</tr>";
                return row;
            }
        });
    </script>
</head>
<body>
    <table>
        <tbody>
            <tr>
                <td><input type="text" id="prodId" placeholder="Search By Product Id" /></td>
                <td><input type="submit" id="Search" value="Search" /></td>
            </tr>
        </tbody>
    </table>
    <table id="product" border="1">
        <tbody>
        <thead>
            <tr>
                <td>Product Id</td>
                <td>Product Name</td>
                <td>Product Code</td>
                <td>Product Qty</td>
                <td>Product Weight</td>
                <td>Product Desc</td>
            </tr>
        </thead>
        </tbody>
    </table>
</body>
</html>

Right-click TestWebApiDemo.html file in Solution Explorer and Click on “Set As Start Page”

ALL Done

Note:-

Calling / Consuming the api used either Ajax or Json call.

JSON

    <script>
        $(document).ready(function () {
            var row = "";
            var uri = 'api/product';

            $.getJSON(uri)
                .done(function (data) {
                    $.each(data, function (key, item) {
                        row += formatItem(item);
                    });
                    $("#product tbody").append(row);
                }).fail(function (jqXHR, textStatus, err) {
                    alert(err);
                });

            $("#Search").click(function () {
                var prodId = $('#prodId').val();

                if (prodId === "" || isNaN(prodId)) {
                    alert("Enter valid ProductId");
                }
                else {
                    $.getJSON(uri + '/?prodId=' + prodId)
                    .done(function (data) {
                        $("#product tbody tr").remove();
                        $("#product tbody").append(formatItem(data));
                    })
                    .fail(function (jqXHR, textStatus, err) {
                        alert(err);
                    });
                }
            });

            function formatItem(item) {
                var row = "<tr>";
                row += "<td>" + item.ProductId + "</td>";
                row += "<td>" + item.ProductName + "</td>";
                row += "<td>" + item.ProductCode + "</td>";
                row += "<td>" + item.ProductQty + "</td>";
                row += "<td>" + item.ProductWeight + "</td>";
                row += "<td>" + item.ProductDesc + "</td>";
                row += "</tr>";
                return row;
            }
        });
    </script>

Ajax

    <script>
        $(document).ready(function () {
            var row = "";
            var uri = 'api/product';

            $.ajax({
                type: "GET",
                url: uri,
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (key, item) {
                        row += formatItem(item);
                    });
                    $("#product tbody").append(row);
                },
                fail: function (jqXHR, textStatus, err) {
                    alert(err);
                }
            });

            $("#Search").click(function () {
                var prodId = $('#prodId').val();

                if (prodId === "" || isNaN(prodId)) {
                    alert("Enter valid ProductId");
                }
                else {
                    $.ajax({
                        type: "GET",
                        url: uri,
                        data: { prodId: prodId },
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            $.each(data, function (key, item) {
                                row += formatItem(item);
                            });
                            $("#product tbody tr").remove();
                            $("#product tbody").append(formatItem(data));
                        },
                        fail: function (jqXHR, textStatus, err) {
                            alert(err);
                        }
                    });
                }
            });

            function formatItem(item) {
                var row = "<tr>";
                row += "<td>" + item.ProductId + "</td>";
                row += "<td>" + item.ProductName + "</td>";
                row += "<td>" + item.ProductCode + "</td>";
                row += "<td>" + item.ProductQty + "</td>";
                row += "<td>" + item.ProductWeight + "</td>";
                row += "<td>" + item.ProductDesc + "</td>";
                row += "</tr>";
                return row;
            }
        });

    </script>

Run Project

Output