How to Develop an ASP.NET Web Service Application with WCF Service
In this article, I am going to explain how to develop a RESTFul web service server application in C#.
Join the DZone community and get the full member experience.
Join For FreeIn this article, I am going to explain how to develop RESTFul web service server application in C#. Here, I will explain how to handle GET, POST, PUT and DELETE requests. This article is very simply designed so that it would be easy for everyone to understand. You can download the project from here.
If you are interested in learning more about RESTFul services and JSON, you can read the below articles.
What is a RESTFul service?
I have written two more articles on RESTFul web service in .net, you might like them.
Let’s start our project.
1. First, create an ASP.NET Web Application project in Visual Studio and name it StudentRegistrationDemo1.
File->New->Project->ASP.NET Web Application (see below window) and click ok.
Once you click the OK button, you can see the below window
You just click OK and create an empty project.
Now your project framework is created and you can see it in your Solution Explorer
2. Now create a folder named Dataobjects. Here, we will create all the classes to hold our Student Registration information. We are not using a database in this example.
3. First, create a Folder called Dataobject to store all the classes we required for this project. Right-click on the project in the above Solution Explorer and select Add, and from the sub-window, select New Folder and name it Dataobject.
4. Our first C# class would be "Student class" to create a student object to store information of a student. Right-click on the Dataobject folder in the above Solution Explorer and select Add. From the sub window, select Class, and you can see the below window. Now give this class the name Student and click the Add button.
Now add the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace StudentRegistrationDemo1.Dataobject
{
[Serializable]
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; }
}
}
}
5. Our 2nd class would be StudentRegistration. This is a singleton class, and it will hold the list of registered students and all the operations for GET, POST, PUT, and DELETE requests. Just follow step 4 above to create this class. Now add the below codes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace StudentRegistrationDemo1.Dataobject
{
public class StudentRegistration
{
Dictionary<string, Student> studentList;
static StudentRegistration stdregd = null;
private StudentRegistration()
{
studentList = new Dictionary<string, Student>();
}
public static StudentRegistration getInstance()
{
if (stdregd == null)
{
stdregd = new StudentRegistration();
return stdregd;
}
else
{
return stdregd;
}
}
public void Add(Student student)
{
studentList.Add(student.RegistrationNumber, student);
}
public Student Remove(String registrationNumber)
{
Student std;
std = studentList[registrationNumber];
studentList.Remove(registrationNumber);
return std;
}
public Dictionary<string, Student> getAllStudent()
{
return studentList;
}
public Student getStudent(String registrationNum)
{
return studentList[registrationNum];
}
public String UpdateStudent(Student std)
{
String reply = "Student List Updated successfully";
studentList[std.RegistrationNumber] = std;
return reply;
}
}
}
6. Now we need a class to respond back to calls for POST. Whenever we will add a student record, it will return the below object with information of the student that has added to the system.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace StudentRegistrationDemo1.Dataobject
{
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; }
}
}
}
Now we need all the controllers to implement GET, POST, PUT, and DELETE web service calls.
7. Now right-click on the project and add a folder called “Controllers” (follow step 3). This folder will hold all the necessary controller classes for GET, POST, PUT, and DELETE services. We will create a separate controller for GET, POST, PUT, and DELETE requests in this example even though it's not necessary, but we are showing them 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 is easy to maintain and debug the application. First, start with the GET request. Here, we will create our first controller to handle the GET request and name it StudentRetrieveController.
8. Now right-click on the folder “Controllers” in the Solution Explorer and select Add->NewItem. Now you can see the below Window, and from that, select "WCF Service (Ajax-enabled)" and click the Add button. WCF stands for Windows Communication Foundation. WCF is a library for applications of various platforms or the same platform to communicate over the various protocols such as TCP, HTTP, HTTPS. Ajax is basically Asynchronous JavaScript and XML. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes.
Now open the controller class and add the below code after the comment // Add more operations here and mark them with [OperationContract] to handle a GET request.
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json,
UriTemplate = "/GetAllStudents/", ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
public Dictionary<string, Student> GetAllStudents()
{
return StudentRegistration.getInstance().getAllStudent();
}
Each time you add a controller class, please add it below the first line in the “using” section: Using StudentRegistrationDemo1.Dataobject;
9. Now we need to make a configuration change to enable this RESTFul web service. Please do not forget to make these changes when you add a controller or else your services will not work at all.
From Solution Explorer, click and open Web.config and find <enableWebScript>
Change it to <webHttp />
10. Now is the time to run and test our first service. 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.
Now a browser window will open like below:
Don’t be disappointed to see the above window and do not close it. Now the server is running and we will do our first web service call i.e. GET service call first. Just copy and paste the below URL on the address bar and hit the enter button (Please keep in mind that port number must be different in your case. In my case, it is 53572. Change it accordingly). Now you can see the below:
http://localhost:53572/Controllers/StudentRetriveController.svc/GetAllStudents/
As we did not insert any records into our application, we see an empty JSON record. So far so good. Let's add a POST service to store student information in our system. Just stop the application.
11. Now follow step 8 and add a new controller called StudentRegistrationController for handling the HTTP request for POST calls. Once you create this controller, immediately follow step 9 and modify the web-config.xml file and add the below code in the controller class. Each time you add a controller class, please add the below line first in the “using” section.
using StudentRegistrationDemo1.Dataobject;
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/register.json")]
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 for the POST web service call, we will use the SOAPUI tool. Download the soap from here and install it in your system. It's better to use the open source version, which is free.
Now the real testing part:
12. Open the SOAPUI tool and go to file and select “New REST project.” A small window will appear like below, where you paste the below URL: http://localhost:53572/Controllers/StudentRegistrationController.svc/register.json for POST service call and click ok.
Now you can see the below window:
Now, first select Method as POST (By default it will display GET) and add below JSON block in “Media Type” window also from the combo box select media type as application/json.
{
“name”: “someName”,
“age”: 25,
“registrationNumber”: “12345”
}
Now click the green arrow button, which will add the record to your system. Repeat this to insert 3 records with different values. Please keep in mind we have not used any exception handling here, hence, the registration number must be different each time.
After inserting 3 records, we will execute the GET call to see all these records.
13. Now follow step 12 and create a project to test the GET request. Just copy and paste the below URL. Here, you don’t need to do anything just click the green arrow button.
http://localhost:53572/Controllers/StudentRetriveController.svc/GetAllStudents/
In the above image, I have inserted three records, and in one record, I put the age as 100 so that I can modify it with the PUT call.
14. Now add a new controller called StudentUpdateController and modify the Web.config file as mentioned in step 9 and add the below code in the controller class to handle PUT request.
[WebInvoke(Method = "PUT",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/Update.json")]
public String updateStudent(Student studentregd)
{
try
{
return StudentRegistration.getInstance().UpdateStudent(studentregd);
}
catch (Exception e)
{
return e.Message;
}
}
15. Now again, restart the server and insert 3 records. Then create one project for the PUT service call and add the records to be modified and click the green arrow button.
http://localhost:53572/Controllers/StudentUpdateController.svc/Update.json
Now follow step 13 and check the modified record.
16. Now, our last web service call is DELETE. Add a new controller called StudentDeleteController and add the below code. Modify web.config file and restart the server. Add three records and delete any one of them and check.
[OperationContract]
[WebInvoke(Method = "DELETE",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/delete.json/{registrationNumber}")]
public Student DeleteStudent(String registrationNumber)
{
return StudentRegistration.getInstance().Remove(registrationNumber);
}
Use the below URL and create a project for the DELETE web service call
http://localhost:53572/Controllers/StudentDeleteController.svc/delete.json/12346
In the above URL, 12346 is the registration number of a student.
In this article, I have not implemented any Exception Handler. I am leaving it to you as an exercise. Whenever implementing an exception handler in Web APIs, always keep in mind that your return type must be a generic type. In case of an exception, you might not return the actual return type but an Exception object or even a string. For example, in the below POST call, in the event of an exception, you are not going to return an object type "StudentRegistrationReply", rather, you will return an Exception object or an error message as a string object. Hence, you have to change the return type to IActionResult.
public IActionResult registerStudent(Student studentregd)
{
//now you can return any object type
}
Also, I want you to implement a GET request, which will return a particular student based on his registration number.
I am giving you the example of the URLs for the same below:
http://localhost:53572/Controllers/StudentRetriveController.svc/GetStudent/12345
http://localhost:53572/Controllers/StudentRetriveController.svc/GetStudent?registrationNumber=12345
Thank you, and let me know of any questions in the comments.
Opinions expressed by DZone contributors are their own.
Trending
-
How to Submit a Post to DZone
-
DZone's Article Submission Guidelines
-
Avoiding Pitfalls With Java Optional: Common Mistakes and How To Fix Them [Video]
-
Auditing Tools for Kubernetes
Comments