Create a RESTful WCF Service
1. Open Visual Studio, click File > New > Project
2. Select WCF Service Library template under Visual C# > WCF templates
3. Change the name to StudentServiceLibrary and click OK
4. Visual studio will add reference to System.ServiceModel, System.Runtime.Serialization and will add some files with sample code.
5. Delete IService1.cs and Service1.cs
6. Add reference to System.ServiceModel.Web
7. Add a new class called StudentService
Adding Data Contract
8. Open StudentService.cs file that you created and add the following code
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
9. Add the following code in the StudentService.cs class
namespace StudentServiceLibrary
{
[DataContract]
public class Student
{
[DataMember]
public string StuId { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string Email { get; set; }
}
class StudentService
{
}
}
Adding Service Contract
10. Add the following code in the StudentService.cs class
[ServiceContract]
public interface IStudentService
{
[WebInvoke(Method = "POST", UriTemplate = "student")]
[OperationContract]
void AddStudent(Student pr);
[WebGet(UriTemplate = "students")]
[OperationContract]
IEnumerable<Student> ListAllStudent();
[WebGet(UriTemplate = "students/{stuId}")]
[OperationContract]
Student GetStudentById(string stuId);
}
Service Implementation
11. Add the following code in the ProductService.cs class
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class StudentService : IStudentService
{
Dictionary<string, Student> Students = new Dictionary<string, Student>();
public void AddStudent(Student stu)
{
Students.Add(stu.StuId, stu);
}
public IEnumerable<Student> ListAllStudent()
{
return Students.Values;
}
public Student GetStudentById(string stuId)
{
return Students[stuId];
}
}
Service endpoints
12. Updated the name of the service in App.config as shown below:
Comments
Post a Comment