Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Create a WCF REST Service C#

In this article, you will learn how to create a Wcf Rest service – C# ASP.Net step by step with an example. REST stands for Representational state transfer which is a technique to communicate on cross-platform application and exchange the data in JSON or XML format.

  • Keep reading on How to create Web API in ASP.NET C#

Let’s understand the HTTP methods which is most commonly used to create a WCF REST service:

  • GET: Get the records from a particular source such as SQL Server database.
  • POST: It is used to insert the records into a particular source such as SQL Server/Oracle database.
  • PUT: It is used to modify the resource or records.
  • DELETE: Used to delete the specific resource or record from a particular source.

I hope you got an idea of the REST concept. For more in detail refer to HTTP Request Methods

How to Create a WCF REST Service – C#

Now let’s get started with creating a rest wcf service in the c# asp.net application. Follow the below steps:-

Step 1: Create New Project and select WCF Service Application as shown below in the screenshot:-Step 2: Preparing the data to return

Now add a new class to the newly created project. Name it to Customers. cs. This class will contain two things. The first one is Data Contract and the second one is a singleton implemented class that gets Customers data from a database and returns a list of Customers.

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

namespace WcfRestService
{
    [DataContract]
    public class Customer
    {
        [DataMember]
        public int CustomerId { get; set; }
        [DataMember]
        public string CustomerName { get; set; }
        [DataMember]
        public string CustomerAddress { get; set; }
    }

    public partial class Customers
    {
        private static readonly Customers _obj = new Customers();
        private Customers() { }

        public static Customers Instance
        {
            get
            {
                return _obj;
            }
        }

        public List CustomerList
        {
            get
            {
                return customers;
            }
        }

        private List customers = new List()
        {
         new Customer() { CustomerId = 1, CustomerName = "Dell", CustomerAddress = "Banglore"},
         new Customer() { CustomerId = 2, CustomerName = "Sony", CustomerAddress = "New Delhi"},
         new Customer() { CustomerId = 1, CustomerName = "Apple", CustomerAddress = "USA"},
         new Customer() { CustomerId = 1, CustomerName = "Samsung", CustomerAddress = "China"},
         new Customer() { CustomerId = 1, CustomerName = "Micromax", CustomerAddress = "New Delhi"}
         };
    }
}

Step 3: Add a Service Contract

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfRestService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both the code and config file together.
    [ServiceContract]
    public interface IService1
    {
        // XML format only
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetCustomerListXML")]
        List GetCustomerListXML();

        // JSON format only
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetCustomerListJSON")]
        List GetCustomerListJSON();
    }
}
IService1 contains only two methods i.e. GetCustomerListXML, GetCustomerListJSON. Important points to understand about these methods are WebInvoke attribute parameters.
  • Method = “GET”, represents an HTTP GET request.
  • ResponseFormat = WebMessageFormat.Xml, response format will be XML here but we can return JSON as well by changing its value to WebMessageFormat.Json.
  • BodyStyle = WebMessageBodyStyle.Wrapped, indicates both the request and response are wrapped.
  • UriTemplate = “GetCustomerList/”, it has two parts, URL path and query.

Note: Don’t forget to add using System.ServiceModel.Web namespace.

Step 4: Implementing REST Service

Here, we are going to implement the service. Only two methods GetCustomerListXMLGetCustomerListJSON are defined in the contract, so implementing service class will be as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfRestService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        public List GetCustomerListXML()
        {
            return Customers.Instance.CustomerList;
        }

        public List GetCustomerListJSON()
        {
            return Customers.Instance.CustomerList;
        }
    }
}

Step 5: Configure Service and Behavior

The last step is to configure the service and its behaviors using the configuration file. Following are the complete ServiceModel configuration settings.

webHTTPBinding is the binding used for RESTful services. Now our Restful service is done. Run the WCF Service Application and test it.

Output with JSON formatOutput in XML format

Download Source Code

Conclusion

I hope you liked this article on creating wcf rest service – c# example. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

The post Create a WCF REST Service C# appeared first on DotNetTec.



This post first appeared on Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps API Developer, please read the originial post: here

Share the post

Create a WCF REST Service C#

×

Subscribe to Asp Dot Net Tricks And Tips, Dot Net Coding Tips, Google Maps Api Developer

Get updates delivered right to your inbox!

Thank you for your subscription

×