ProgrammerGuide.Net | Step by Step Programmer Guide

CREATING WCF RESTFUL SERVICE

Restful service follows the REST (Representational State Transfer) architectural style and approach to communications often used in web service developments. This service allows us to make calls and exchange data using SOAP (Simple Object Access Protocol).

A restful API (Application Program Interface) uses http method requests to Get, Put, Post and Delete data. An API for a website is a code which allows two softwares to connect and communicate with each other. Restful APIs are used by the websites of many big multinational companies like Amazon, Google, LinkedIn, Twitter, etc.

In this article, we will be learning how to create WCF Rest multiple parameters post step by step right from the beginning. Let’s look into the following steps:

  1. Open Microsoft Visual Studio and create a new project console application.
  2. Edit the app.config code like as shown below:
  1. Next create IService.cs for interface class as shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;namespace restwcf
{
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(UriTemplate = "postuser",
ResponseFormat = WebMessageFormat.Json)]
string PostUser(USER data);
}public class USER
{
public string username { get; set; }
public string password { get; set; }
public string firstname { get; set; }
public string lastname { get; set; }
}
}
  1. In case if you get an error, open reference manager and add reference as shown :
  2. Now create a new file with name Service.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace restwcf
{
public class Service : IService
{
public string PostUser(USER data)
{
try
{
string result = "";
//Function insert database
result = "You have been post api with wcf restful!";
return result;
}
catch (Exception ex)
{
return null;
}
}
}
}
  1. Edit program class as shown:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;
using System.Threading.Tasks;namespace restwcf
{
class Program
{
static void Main(string[] args)
{
WebServiceHost hostWeb = new WebServiceHost(typeof(restwcf.Service));
ServiceEndpoint ep = hostWeb.AddServiceEndpoint(typeof(restwcf.IService), new WebHttpBinding(), "");
ServiceDebugBehavior stp = hostWeb.Description.Behaviors.Find();
stp.HttpHelpPageEnabled = false;
hostWeb.Open();Console.WriteLine("Service Host started @ " + DateTime.Now.ToString());Console.Read();
}
}
}
  1. Now run the application with Debug or Release mode.
Please click here for related products on Amazon!

Jayashee

Add comment

Want to Check Celebrities News?