Skip to main content

Creating and consuming asp.net web api services

Hi buddy, greetings to you all.

If you are newbie in asp.net Web API, today you will learn Microsoft hottest service technology named “Web API” or you are expert, please read this post and leave a comment.

So let’s start:

Microsoft Asp.net Web API is a wonderful framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is the best platform for building RESTful applications on the .NET Framework.  Web Api service not impose client-side object proxy requirements. One of the best things is it supports JSON and XML formats out-of-the-box for data transfer over the wire.

Buddy for your understanding, express a real scenario:

 “We have a student list for different Institutes/schools where each institute/school is under an Education board. Each student can choose only one group form “Science, Business Studies and Humanities” that means a student can study only one group. Students have subject-wise number who already achieved by examination.”

I think you understood now, this system containing student information with school, board, group and also subject wise results.

The government wants to expose a service only for a few days to publish the results with basic parameters.

So, in this regard, I will make an Asp.net Web API service where student select their own board and also give own role no and service will provide them subject wise Grade.

For this above scenario, we find out Entities:
  • Education Board
  • Institute
  • Group
  • Subject
  • Student
  • ResultSheet 


Figure: ERD diagram

I will not create any database for this. We will make temporary data in TempData class. Conceptually we make relational data list.

Here we will use Visual Studio 2015.

Let’s go enjoying……….😊

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.

In the new project dialog, select installed template, expand this and select web. Select Asp.Net Web Application; give project name “ResultService” and click ok.




In the new ASP.NET Web Application dialog select Empty template, Checked Web API and click OK.




Adding model

Simply saying, Model used to back response under the client request. Model is an object that Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message.

If the solution explorer visible,right click Model,click add then selct Class.
  


 Give class name Board and add board Properties.


According to “Board” Model we will add other model from ERD entity.

Board Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ResultService.Models
{
    /// <summary>
    /// Education baord
    /// www.codebyexperience.com
    /// date:31-jul-2017
    /// </summary>
    public class Board
    {
        public Int64 Id { get; set; }
        public string BoardName { get; set; }
       
    }
}


Institute Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ResultService.Models
{
    public class Institute
    {
        public Int64 Id { get; set; }
        public string InstituteName { get; set; }
        public Int32 EIIN { get; set; }
        public string Phone { get; set; }
        public string Adress { get; set; }
        public string District { get; set; }
        public Int32 BoardId { get; set; }
    }
}

Group Model:           

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ResultService.Models
{
    public class Group
    {
        public Int64 Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }       
    }
}


Student Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ResultService.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime DateofBirth { get; set; }
        public string FatherName { get; set; }
        public string MotherName { get; set; }
        public Int64 GroupId { get; set; }
        public Int64 RoleId { get; set; }
        public Int64 RegistrationNo { get; set; }
        public Int64 InstitutionId { get; set; }
        public string BoardName { get; set; }
    }
}

Subject Model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ResultService.Models
{
    public class Subject
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int GroupId { get; set; }
    }
}


Result Sheet Model:  here I have added new properties SubjectGrade that calling a method and retrun Grade.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ResultService.Models
{
    public class ResultSheet
    {
        public int Id { get; set; }
       
        public Int64 StudentId { get; set; }      
        public int SubjectId { get; set; }
        public decimal Mark { get; set; }
        public string SubjectGrade
        {
            get
            {
                return GradeCalculation(Mark);
            }
        }

        /// <summary>
        /// Number wise grade
        /// </summary>
        /// <param name="mark"></param>
        /// <returns></returns>
        private string GradeCalculation(decimal mark)
        {
            string grade = "F";

            if (mark >= 80)
            {
                grade = "A+";
            }
            else if (mark >= 70 && mark <= 79)
            {
                grade = "A";
            }
            else if (mark >= 60 && mark <= 69)
            {
                grade = "A-";
            }
            else if (mark >= 50 && mark <= 59)
            {
                grade = "B";
            }
            else if (mark >= 40 && mark <= 49)
            {
                grade = "C";
            }
            else if (mark >= 33 && mark <= 39)
            {
                grade = "D";
            }
            else if (mark < 33)
            {
                grade = "F";
            }
            return grade;
        }

    }

}

Add StudentResultData: An extra model for using response message.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ResultService.Models
{
    public class StudentResultData
    {        public string SubjectName { get; set; }
        public decimal Mark { get; set; }
        public string SubjectGrade { get; set; }
        public Int64 RoleId { get; set; }
        public Int64 RegistrationNo { get; set; }
        public string StudentName { get; set; }
        public DateTime DateofBirth { get; set; }
        public string GroupName { get; set; }
        public string InstitueName { get; set; }
        public string BoardName { get; set; }
    }
}

Temporary data: Now create temporary data. Create folder named Data. Add new class named TempData. Creating array list for stuents, Subject,group, institute, board and student wise ResultSheet. We will create data according to ERD maintain Relational database (logically ).

using ResultService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ResultService.Data
{
    public class TempData
    {

        // Subject data
        Subject[] subjects = new Subject[]
               
        {
              new Subject { Id = 1,GroupId=0,Name="Bangla" },
              new Subject { Id = 2,GroupId=0,Name="English" },
              new Subject { Id = 3,GroupId=0,Name="General Math" },
           
                  // Science Grop Subjects
              new Subject { Id = 4,GroupId=1,Name="Higher Math" },
              new Subject { Id = 5,GroupId=1,Name="Physics" },
              new Subject { Id = 6,GroupId=1,Name="Chemistry" },
              new Subject { Id = 7,GroupId=1,Name="Biology" },
              new Subject { Id = 8,GroupId=1,Name="Computer" },
              
                   // Commerce Group
              new Subject { Id = 12,GroupId=2,Name="Accounting" },
              new Subject { Id = 13,GroupId=2,Name="Business Communication" },
              new Subject { Id = 14,GroupId=2,Name="Business Management" },
              new Subject { Id = 15,GroupId=2,Name="ICT" },
              new Subject { Id = 16,GroupId=2,Name="Finance" },

                  // Humanities Group
              new Subject { Id = 17,GroupId=3,Name="Accounting" },
              new Subject { Id = 18,GroupId=3,Name="Business Communication" },
              new Subject { Id = 19,GroupId=3,Name="Business Management" },
              new Subject { Id = 20,GroupId=3,Name="ICT" },
         };

        /*Sections -- science, Commerce */
        Group[] groups = new Group[]
        {
            new Group {Id=0,Name="Common",Description="Mendatory for all Group" },
            new Group {Id=1,Name="Science",Description="Science" },
            new Group {Id=2,Name="Commerce",Description="Commerce" },
            new Group {Id=3,Name="Humanities",Description="Humanities " },
        };

        /*Student Data*/
        Student[] students = new Student[]
        {
            new Student {Id=16,RoleId=321456,RegistrationNo=654123,InstitutionId=321,Name = "Mohammad Maksud",FatherName="Md Hassan",MotherName="Ismat Jahan",DateofBirth=Convert.ToDateTime("01-Aug-2001"),GroupId=1},
            new Student {Id=1,RoleId=321455,RegistrationNo=554123,InstitutionId=321,Name = "Mohammad Shamim Eskander",FatherName="Md Akter uz- zaman",MotherName="Ismat Jahan",DateofBirth=Convert.ToDateTime("01-July-2001"),GroupId=1},
            new Student {Id=2,RoleId=321454,RegistrationNo=754123,InstitutionId=325,Name = "Tuhi raben",FatherName="Md Rubel Islam",MotherName="Turat islam",DateofBirth=Convert.ToDateTime("01-Sep-2001"),GroupId=1},
            new Student {Id=3,RoleId=321453,RegistrationNo=854123,InstitutionId=325,Name = "Rumki Akter",FatherName="Jewel Islam",MotherName="Ekran Hossan ",DateofBirth=Convert.ToDateTime("01-Dec-2001"),GroupId=2},
            new Student {Id=4,RoleId=321440,RegistrationNo=954123,InstitutionId=321,Name = "Rubai Hossain",FatherName="Md Hassan",MotherName="Piyara Begum",DateofBirth=Convert.ToDateTime("01-Sep-2001"),GroupId=1},
            new Student {Id=5,RoleId=321441,RegistrationNo=154123,InstitutionId=325,Name = "Mohammad kafi Ahmen",FatherName="Kabir bhuiya",MotherName="Jannatul Ferdaus",DateofBirth=Convert.ToDateTime("01-July-2001"),GroupId=1},
            new Student {Id=6,RoleId=321443,RegistrationNo=254123,InstitutionId=321,Name = "Mohammad Jahangir",FatherName="Ajgar ali",MotherName="Ismat Jahan",DateofBirth=Convert.ToDateTime("01-Jul-2001"),GroupId=2},

            new Student {Id=7,RoleId=321416,RegistrationNo=354223,InstitutionId=325,Name = "Muhammad Ashik",FatherName="Hasnath Takbir",MotherName="Mariam Begum",DateofBirth=Convert.ToDateTime("01-Jul-2001"),GroupId=1},
            new Student {Id=8,RoleId=321426,RegistrationNo=454323,InstitutionId=325,Name = "Rumpom Banik",FatherName="Dev banik",MotherName="Turain Banik",DateofBirth=Convert.ToDateTime("01-Sep-2001"),GroupId=3},
            new Student {Id=9,RoleId=321436,RegistrationNo=641443,InstitutionId=325,Name = "Shibasis Paul",FatherName="Bijoy Paul",MotherName="Anfesa Paul",DateofBirth=Convert.ToDateTime("01-Jul-2001"),GroupId=3},
            new Student {Id=11,RoleId=321422,RegistrationNo=654523,InstitutionId=321,Name = "Adaram pal krisno",FatherName="Mahur lal sarkar",MotherName="Evri paul",DateofBirth=Convert.ToDateTime("01-July-2001"),GroupId=1},

            new Student {Id=12,RoleId=421456,RegistrationNo=652123,InstitutionId=321,Name = "Hassan bin Turja",FatherName="Md Hassan",MotherName="Ismat Jahan",DateofBirth=Convert.ToDateTime("01-Jul-2001"),GroupId=2},
            new Student {Id=13,RoleId=521456,RegistrationNo=624125,InstitutionId=321,Name = "Iasir al jannah",FatherName="Md Maksudur Rahman",MotherName="Jannat",DateofBirth=Convert.ToDateTime("01-Aug-2001"),GroupId=3},
            new Student {Id=14,RoleId=621456,RegistrationNo=624129,InstitutionId=321,Name = "Dinesh Chakma",FatherName="Birum Chakma",MotherName="Akun chakma",DateofBirth=Convert.ToDateTime("01-Jul-2001"),GroupId=3},
            new Student {Id=15,RoleId=821456,RegistrationNo=651023,InstitutionId=321,Name = "Crush Rabben",FatherName="Al-Fred Rassel",MotherName="Rabben Freck",DateofBirth=Convert.ToDateTime("01-Aug-2001"),GroupId=1},
        };

        /* Institute Data */
        Institute[] institutes = new Institute[]
            {
                 new Institute {Id=321,EIIN=5566, Adress="Laxmipur Sadar, laxmipur-3700", InstituteName="Laxmipur Adarsha Samad Govt High school",District="Laxmipur",Phone="024587458",BoardId=50 },
                 new Institute {Id=325,EIIN=7766, Adress="Siyal bari , Mirpur-1216", InstituteName="Monipur School & College",District="Dhaka",Phone="024588958",BoardId=10 },
            };

        /*Board Data */
        Board[] boards = new Board[]
            {
                 new Board {Id=10, BoardName="Dhaka" },
                 new Board {Id=50, BoardName="Comilla" },
            };


        /*Students results data */
        ResultSheet[] resultSheet = new ResultSheet[]
                {
                    new ResultSheet { Id = 1,StudentId=16, SubjectId = 1, Mark = 70, },
                    new ResultSheet { Id = 2,StudentId=16, SubjectId = 2, Mark = 75, },
                    new ResultSheet { Id = 3,StudentId=16, SubjectId = 3, Mark = 80, },
                    new ResultSheet { Id = 4,StudentId=16, SubjectId = 4, Mark = 79, },
                    new ResultSheet { Id = 5,StudentId=16, SubjectId = 5, Mark = 90, },
                    new ResultSheet { Id = 6,StudentId=16, SubjectId = 6, Mark = 65, },
                    new ResultSheet { Id = 7,StudentId=16, SubjectId = 7, Mark = 77, },
                    new ResultSheet { Id = 8,StudentId=16, SubjectId = 8, Mark = 71, },

                    new ResultSheet { Id = 9,StudentId=3, SubjectId = 1, Mark = 70, },
                    new ResultSheet { Id = 10,StudentId=3, SubjectId = 2, Mark = 75, },
                    new ResultSheet { Id = 12,StudentId=3, SubjectId = 3, Mark = 80, },
                    new ResultSheet { Id = 11,StudentId=3, SubjectId = 12, Mark = 79, },
                    new ResultSheet { Id = 13,StudentId=3, SubjectId = 13, Mark = 90, },
                    new ResultSheet { Id = 14,StudentId=3, SubjectId = 14, Mark = 65, },
                    new ResultSheet { Id = 15,StudentId=3, SubjectId = 15, Mark = 77, },
                    new ResultSheet { Id = 16,StudentId=3, SubjectId = 16, Mark = 71, },

                };


        // return all students
        public IEnumerable<Student> GetAllStudent()
        {
            return students;
        }

        // Return all Group
        public IEnumerable<Group> GetAllGroup()
        {
            return groups;
        }

        // Return all Subjects
        public IEnumerable<Subject> GetAllSubject()
        {
            return subjects;
        }
        // Return All Boards
        public IEnumerable<Board> GetAllBoards()
        {
            return boards;
        }

        public IEnumerable<StudentResultData> StudentResult(Int32 roleId,Int32 boardId )
        {

            var result = (from rs in resultSheet
                        join st in students on rs.StudentId equals st.Id
                        join sub in subjects on rs.SubjectId equals sub.Id
                        join gp in groups on st.GroupId equals gp.Id
                        join ins in institutes on st.InstitutionId equals ins.Id
                        //join bor in boards on ins.BoardId equals bor.Id
                        where st.RoleId == roleId && ins.BoardId == boardId
                        select new StudentResultData
                        {
                            SubjectGrade = rs.SubjectGrade,
                            Mark = rs.Mark,
                            RoleId = st.RoleId,
                            StudentName = st.Name,
                            RegistrationNo = st.RegistrationNo,
                            DateofBirth = st.DateofBirth,
                            SubjectName = sub.Name,
                            GroupName = gp.Name,
                            BoardName = (from bord in boards
                                           where bord.Id == boardId select bord.BoardName).FirstOrDefault(),
                            InstitueName=ins.InstituteName,
                        }).ToList();

            return result;
        }


    }


}


Add Controler:

In asp.net Web API, the controler handled all HTTP request. Now we will add StudentResultController controller that hold two methods one return all Board and another return strudent result by role no. In the solution explorer right click Controller , Add Controller.




In the New opened wizard Add Scaffold , select Web API 2 Controller –Empty and Click Add



In the Add Controller dialog, name the controller "StudentResultController". Click Add.


Now adding two methods those are to expose to public.

using ResultService.Data;
using ResultService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace ResultService.Controllers
{
    public class StudentResultController : ApiController
    {

        TempData data = new TempData();

        [HttpGet]
        public IEnumerable<Board> GetAllBoards()
        {
            return data.GetAllBoards();
        }

        [HttpGet]
        public IHttpActionResult GetStudentResult(Int32 id, Int32 boardId)
        {
           
            var result = data.StudentResult(id, boardId);
           
            if (result == null)
            {
                return NotFound();
            }
            //var xml = Configuration.Formatters.XmlFormatter;
            return Content(HttpStatusCode.OK, result, Configuration.Formatters.JsonFormatter);
        }
    }
}

Now almost done, first time build the solution. So now I will add an html “index.html” file where consume this service.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>Student Result</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script src="Scripts/bootstrap.min.js"></script>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/bootstrap-theme.min.css" rel="stylesheet" />
</head>
<body>
    <div class="container-fluid" style="height:200px;">
        <div class="row">

        </div>
    </div>
    <div class="container-fluid" style="width:80%; ">
        <div class="row bg-info" style="padding-top:10px;padding-bottom:5px;">
            <div class="col-lg-4 col-sm-12 text-right"> Select Board</div>
            <div class="col-lg-3 col-sm-12"><select id="boards" class="form-control"></select></div>
        </div>
        <div class="row bg-info" style="padding-bottom:10px;">
            <div class="col-lg-4 col-sm-12 text-right">Role No</div>
            <div class="col-lg-3"><input type="text" id="RoleId" size="6" class="form-control" placeholder="Student Role" /></div>
            <div class="col-lg-2"><input type="button" value="Search" onclick="findResult();" class="btn btn-default glyphicon glyphicon-search" /></div>
        </div>
        <div class="row bg-primary">
            <div class="col-lg-4 text-right"><h3>Name:</h3> </div>
            <div class="col-lg-6" id="stdName"></div>
        </div>
        <div class="row bg-primary">
            <div class="col-lg-4 text-right"><h3>School Name:</h3> </div>
            <div class="col-lg-6" id="instName"></div>
        </div>
        <div class="row">
            <div class="col-lg-12 table table-bordered table-condensed table-hover">
                <div class="row ">
                    <div class="col-lg-3 "></div>
                    <div class="col-lg-6 ">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Subject</th>
                                    <th>Grade</th>
                                </tr>
                            </thead>
                            <tbody id="stdresult">
                                <tr>
                                    <td></td>
                                    <td></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="col-lg-3 "></div>

                </div>
            </div>
            <div class="col-lg-2"></div>
        </div>

    </div>

<script type="text/javascript">
        var uri = 'api/StudentResult';


        /*Get board data and fill in select list*/
        $(document).ready(function () {
            // Send an AJAX request
            $.getJSON(uri)
               .done(function (data) {
                   $('<option>', { text: "Select...", value: "" }).appendTo($('#boards'));
                   $.each(data, function (key, item) {
                       $('<option>', { text: item.BoardName, value: item.Id }).appendTo($('#boards'));

                   });
               });
        });

        function findResult() {
            var id = $('#RoleId').val();
            var boardId = $('#boards').val();

            if (boardId == '') {
                alert('Select board.');
                return;
            }

            if (id == '') {
                alert('Give valid role No.');
                return;
            }


            $('#stdName').empty();
            $('#instName').empty();
            $('#stdresult').empty();       

            $.getJSON(uri, { id: id, boardId: boardId })
                .done(function (data) {

                    if (data)
     {
                        var item = data[0];
                        $('<h3>' + item.StudentName + '</h3>').appendTo('#stdName');
                        $('<h3>' + item.InstitueName + '</h3>').appendTo('#instName');
                    };

                    $.each(data, function (key, item) {
                        $('<tr>'
                            + '    <td>' + item.SubjectName + '</td>'
                            + '   <td>' + item.SubjectGrade + '</td>'
                            + '</tr>').appendTo($('#stdresult'));

                    });
                })
                .fail(function (jqXHR, textStatus, err) {
                    $('#studentResult').text('Error: ' + err);
                });
        }
    </script>
</body>
</html>

Please look function “findResult()” where calling “GetStudentResult” method of the service based on parameter of HttpGet method.

Now full complete done Web Api service for student result and also consuming with jquery ajax in index.html page.

Now go debug and click start debugging or press F5. Now see your browser:




Now, you can host this service as like as asp.net web application. You can build your business service and host it in live. There are many popular hosting providers are available in the web world.

UK Dedicated Servers



Comments

Popular posts from this blog

Database View

View is a database object also called a logical table. it has no psychical existence. It is not like a simple table, but is a virtual or logical table which contains columns and data from different tables (may be one or more tables). A View does not contain any data, it is a set of queries that are applied to one or more tables that is stored within the database as an object. After creating a view from some table(s), it used as a reference of those tables and when executed, it shows only those data which are already mentioned in the query during the creation of the View. Creating view Syntax: ------------------------------------------------- CREATE VIEW [View_Name] AS [ SELECT Statement] ------------------------------------ ------------- CREATE VIEW SampleView As SELECT EmpID, EmpName FROM EmpInfo -------------------------------------------------- Data retrieve from view: SELECT * FROM SampleView WHERE EmpID ='FN0009C1'     View does not modif

Efficiently Paging Through Large Amounts of Data (PageIndex, Page Size) -SQL Server

In this article you learn how to fetch data according PageIndex and PageSize. In web application, it is much more important to increase webform performance, loadbalance. In my development experience, some of table hold large amount of records (more than 2GB) and user need to shows records in GridView. But problem is when we select all records and loads in webforms, webform has crashed. In that case, I will simply solved with Table Variable and using Grid Page Number and Page Size. 1. Create Procedure CREATE PROCEDURE Load_Data_WithPaging @PageIndex AS INT , /*Selected Row Index of selected grid*/ @PageSize AS INT , /*Total page size of selected grid*/ @TotalRecords AS INT OUT /*used for display virtual page no*/ AS BEGIN SET NOCOUNT ON ; DECLARE @FromIndex AS INT = 0 , @ToIndex AS INT = 0 ; SET @FromIndex = (@PageIndex * @PageSize) + 1 ; /*First row no selection*/ SET @ToIndex = ((@PageIndex

What is an Index? Explain Custered Index and Non-Clustered Index

Index Index is a database object, which can be created on one or more columns (16 Max column combination). When creating the index will read the column(s) and forms a relevant data structure to minimize the number of data comparisons. The index will improve the performance of data retrieval and adds some overhead on data modification such as create, delete and modify. So it depends on how much data retrieval can be performed on table versus how much of DML ( Insert , Delete and Update ) operations. clustered index A clustered index is something that reorganizes the way records in the table are physically stored. Therefore a table can have only one clustered index. The leaf nodes of a clustered index contain the data pages, by which I mean the key-value pair in the clustered index has the index key and the actual data value. Also remember, a clustered index will be created on a table by default the moment a primary key is created on the table. A clustered index is so