Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Develop a RESTful Web Service in ASP .NET Web API

DZone's Guide to

How to Develop a RESTful Web Service in ASP .NET Web API

Let's take a look at a tutorial that explains how to develop a RESTful web service in ASP .NET with a web API.

Free Resource

SnapLogic is the leading self-service enterprise-grade integration platform. Download the 2018 GartnerMagic Quadrant for Enterprise iPaaS or play around on the platform, risk free, for 30 days.

Introduction

One of the most popular distributed architectures in the digital world nowadays is RESTful web service, which is widely used in this sector. As ASP.NET is one of the most popular and widely used technologies in the financial and digital sectors of the UK, I have decided to write this article for those interested in distributed technology. You can download the project from here.

I am going to explain, step-by-step, how to develop a RESTful Web service in ASP .NET with a Web API. 

First, download the latest visual studio in your system. This is free for learning purposes.

Also, download SOAPUI for testing our application from here.

I have written one more article in .net Core, you might like that too.

Let’s start our project:

Step 1

First, create an ASP.NET Web Application project in Visual Studio and name it StudentRegistrationDemo2. For that, select File->New->Project->ASP.NET Web Application (see below window) and click OK.

Image title

Once you click the OK button, you can see the below window from where you need to select Web API and click the OK button. 

Image title

        Once you click the OK Button, it will create the below project structure:

Image title

Step 2

Now we will create the below resource classes for handling our GET, POST, PUT, and DELETE services. Right-click on the Models folder from the project explorer window and select Add=>Class (see below).

Image title

Modify Class Student.cs like below:

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

namespace StudentRegistrationDemo2.Models
{
    public class Student
    {
        String name;

        public String Name
        {
            get { return name; }
            set { name = value; }
        }

        int age;

        public int Age
        {
            get { return age; }
            set { age = value; }
        }

        String registrationNumber;

        public String RegistrationNumber
        {
            get { return registrationNumber; }
            set { registrationNumber = value; }
        }


    }
}

Step 3

Follow the above step 2 to create and add below two classes in Models folder:

The first one is StudentRegistration, this is a singleton class, and it will hold the list of registered students including all the operations for GET, POST, PUT, and DELETE requests. 

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

namespace StudentRegistrationDemo2.Models
{
    public class StudentRegistration
    {
        List<Student> studentList;
        static StudentRegistration stdregd = null;

        private StudentRegistration()
        {
            studentList = new List<Student>();
        }

        public static StudentRegistration getInstance()
        {
            if (stdregd == null)
            {
                stdregd = new StudentRegistration();
                return stdregd;
            }
            else
            {
                return stdregd;
            }
        }

        public void Add(Student student)
        {
            studentList.Add(student);
        }

        public String Remove(String registrationNumber)
        {
            for (int i = 0; i < studentList.Count; i++)
            {
                Student stdn = studentList.ElementAt(i);
                if (stdn.RegistrationNumber.Equals(registrationNumber))
                {
                    studentList.RemoveAt(i);//update the new record
                    return "Delete successful";
                }
            }

            return "Delete un-successful";
        }

        public List<Student> getAllStudent()
        {
            return studentList;
        }

        public String UpdateStudent(Student std)
        {
            for (int i = 0; i < studentList.Count; i++)
            {
                Student stdn = studentList.ElementAt(i);
                if (stdn.RegistrationNumber.Equals(std.RegistrationNumber))
                {
                    studentList[i] = std;//update the new record
                    return "Update successful";
                }
            }

            return "Update un-successful";
        }


    }
}

The second one is class StudentRegistrationReply, this class will be used to reply message to the client application as response.

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

namespace StudentRegistrationDemo2.Models
{
    public class StudentRegistrationReply
    {
        String name;

        public String Name
        {
            get { return name; }
            set { name = value; }
        }
        int age;

        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        String registrationNumber;

        public String RegistrationNumber
        {
            get { return registrationNumber; }
            set { registrationNumber = value; }
        }
        String registrationStatus;

        public String RegistrationStatus
        {
            get { return registrationStatus; }
            set { registrationStatus = value; }
        }
    }
}

Step 4 

Now is the time to introduce controller classes to handle GET, POST, PUT, and DELETE web requests. We will create separate controllers for GET, POST, PUT, and DELETE requests in this example even though it's not necessary, but I am using separate controllers for more clarity. Even one controller would suffice for all the above services, but as per good design principle, we should have a separate controller so that it’s easy to maintain and debug the application too.

Let’s start with the GET and POST request first. Right-click on the Controllers folder and select    Add=>Controller.  From the below window, select Web API 2 Controller — EmptyImage title

Name the first controller as StudentRetriveController and click the Add button (See below).

Image title

Now modify StudentRetriveController like below:

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

using StudentRegistrationDemo2.Models;

namespace StudentRegistrationDemo2.Controllers
{
    //GET api/studentretrive
    public class StudentRetriveController : ApiController
    {
        public List<Student> GetAllStudents()
        {
            return StudentRegistration.getInstance().getAllStudent();
        }
    }
}

If you look into the code, it is so simple. We don't need to exclusively mention whether it is a GET request method or not. It even does not require to mention the resource path. The Web API automatically considers it a GET request as the method name starts with a keyword "Get" (GetAllStudent) and in resource path, it will add "api" at the front and the name of the controller (all in small letters) at its back. So any GET call with resource path "/api/studentretrive" will invoke the above "GetAllStudents" method. But if you implement more than one GET method, you have to clearly mention the resource path.

Step 5

Now is the time to introduce a controller to handle a POST request. Just following step 4 and create StudentRegistrationController and modify it like below:

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

using StudentRegistrationDemo2.Models;

namespace StudentRegistrationDemo2.Controllers
{
    public class StudentRegistrationController : ApiController
    {
        public StudentRegistrationReply registerStudent(Student studentregd)
        {
            Console.WriteLine("In registerStudent");
            StudentRegistrationReply stdregreply = new StudentRegistrationReply();
            StudentRegistration.getInstance().Add(studentregd);
            stdregreply.Name = studentregd.Name;
            stdregreply.Age = studentregd.Age;
            stdregreply.RegistrationNumber = studentregd.RegistrationNumber;
            stdregreply.RegistrationStatus = "Successful";

            return stdregreply;
        }

    }
}

Now we are done with our first stage, and it is the time to test the application.

Step 6

From the menu bar, you can see a green arrow button and you can select a browser installed in your system and click it. It will start your web server and run your web service application.

Image titleWait until you see the browser like below:

Image titleNow the server is running and we will do our first web service call i.e. GET service call first.

Step 7

I hope you already installed SOAPUI in your system. If not, download SOAPUI from here. Now open the application, and from the File menu, select New REST Project (File=>New REST Project) and copy and paste the below URL and change the port number 63053 if it is different in your system. Then click the OK button.

http://localhost:63053/api/studentretrive (Notice the URL. We are using the controller name studentretrive (StudentRetriveController) as resource locator)

Image title

Once the project is created, just click the green arrow button and you can see an empty record like below:

Image title

The reason is obvious, as our Student list is empty. We have to insert a few records here. To add records, we will use our POST service. Let's test our POST service now.

Step 8

Just follow the step 7 and create a new REST project and add the below URL:

http://localhost:63053/api/studentregistration

But here, we need to do some extra configuration. First, select POST from the methods list and add the record in Media Type to insert into the application. Now click the green arrow button: 

Image title

Now repeat step 7 and see:

Image title

Now repeat step 8 and insert a few more records and repeat step 7 to check the result.

Image title

So far so good. Now we are going to complete our last part of this project by adding PUT and DELETE services.

Step 9

Follow step 4 and add two controllers respectively: StudentUpdateController and StudentDeleteController. Modify both like below:

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

using StudentRegistrationDemo2.Models;

namespace StudentRegistrationDemo2.Controllers
{
    public class StudentUpdateController : ApiController
    {
        public String PutStudentRecord( Student stdn)
        {
            Console.WriteLine("In updateStudentRecord");
            return StudentRegistration.getInstance().UpdateStudent(stdn);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

using StudentRegistrationDemo2.Models;

namespace StudentRegistrationDemo2.Controllers
{
    public class StudentDeleteController : ApiController
    {
        [Route("student/remove/{regdNum}")]

        public String DeleteStudentRecord(String regdNum)
        {
            Console.WriteLine("In deleteStudentRecord");
            return StudentRegistration.getInstance().Remove(regdNum);
        }
    }
}

Now, look at the above controller class. What kind of differences do you notice? Route: here, we are using Route to specifically mention the resource location. You might have a question about if we need to add multiple POST or GET services and how to differentiate between each method. No worries, we can do it like below:

First with a different method signature 

With different method signature:

 GetAllStudents(){}//default 

 GetStudent(Student object){} 

 GetStudentRec(String registrationNumber){} 

and by using Route

 [Route("student/remove/{regdNum}")] 

 DeleteStudent(String regdNum){} 

 [Route("student/removeall")] 

 DeleteAllStudent(){} 

Now let's test all the services that we have implemented so far.

Step 10

Now use POST service and add three records. In one of the records, make age=270, which is a wrong entry of course. With a GET call, check the records first. Now we are going to correct the above value with our PUT request test. Create a New REST Project and add the below URL. This time, select the method as PUT and add the record to be modified and click the green arrow button.

http://localhost:63053/api/studentupdate

Image title

Now verify the records:

Image title

We have reached the end of our project. Now let's test the DELETE request. Create a new project and add the below URL, and this time, select method type DELETE.

http://localhost:63053/student/remove/12346

Image title

Now just repeat the GET request call and check the result.

Hope you liked this article. Let me know any questions you might have in the comments section. Thanks!

Download A Buyer's Guide to Application and Data Integration, your one-stop-shop for research, checklists, and explanations for an application and data integration solution.

Topics:
web api ,asp .net ,asp.net mvc ,restful api ,integration ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}