How To Create WCF Rest Services In Asp.Net

Representational State Transfer (REST):

  • Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that enable services to work best on the Web. In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.
  • REST is very lightweight, and relies upon the HTTP standard to do its work. It is great to get a useful web service up and running quickly. If you don't need a strict API definition, this is the way to go. REST essentially requires HTTP, and is format-agnostic (meaning you can use XML, JSON, HTML, whatever).

Why SOAP -

Basically SOAP web services are very well established for years and they follow a strict specification that describes how to communicate with them based on the SOAP specification. SOAP (using WSDL) is a heavy-weight XML standard that is centered around document passing. The advantage with this is that your requests and responses can be very well structured, and can even use a DTD. However, this is good if two parties need to have a strict contract (say for inter-bank communication). SOAP also lets you layer things like WS-Security on your documents. SOAP is generally transport-agnostic, meaning you don't necessarily need to use HTTP.

Why Rest Services -

Now REST web services are a bit newer and basically look like simpler because they are not using any communication protocol. Basically what you send and receipt when you use a REST web service is plain XML / JSON through an simple user define Uri (through UriTemplate).

Which and When (Rest Or Soap) -

Generally if you don't need fancy WS-* features and want to make your service as lightweight, example calling from mobile devices like cell phone, pda etc. REST specifications are generally human-readable only.

How to Make Rest Services -

In .Net Microsoft provide the rest architecture building api in WCF application that manage request and response over webHttpBinding protocol here is the code how to create simple rest service through WCF (Only GET http method example).

We can also make our own rest architecture manually through http handler to creating the rest service that would be more efficient and simple to understand what going on inside the rest, we’ll discuss it further at next post.

Just add new WCF application/services or make a website and add a .srv (WCF Service) in it.

CS Part: (IRestSer.cs, RestSer.cs) -

Below is the rest service contract (interface) part and implementation of contract methods part, It is required to add WebInvoke or WebGet attribute on the top of the function that we need to call through webHttpBinding protocol,

Methods include Get, Post, Put, Delete that is http methods.

UriTemplate is required to make fake host for rest service, Uri address actually not exist in real time it is created by WebServiceHostFactory at runtime (when application starts).

Value inside curly braces ({name},{id}) matches with function parameter and Rest api passes value at runtime to corresponding parameters.


IRestSer.cs Part: (Contract Interface):


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

[ServiceContract]
public interface IRestSer
{
   [OperationContract]
   [WebInvoke(Method = "GET", UriTemplate = "/FakeUrl/P1={Name}",
   ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json)]
   string SayHello(string Name);
}


RestSer.cs Part (Implementation of contract)

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

public class RestSer : IRestSer
{
    public string SayHello(string Name)
      {
        return "Hello " + Name;
      }
}

RestSer.svc Part -

Below is the Rest service .svc part where you have to mention factory attribute and set the value (System.ServiceModel.Activation.WebserviceHostFactory) as shown below -

This is required for communication with UriTemplate and makes fake URL host according to UriTemplate.


<%@ ServiceHost Language="C#" Debug="true" Service="RestSer" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>


Need to change binding protocol (webHttpBinding) as rest service call over webHttpBinding protocol only.


  <system.serviceModel>

    <behaviors>
      <serviceBehaviors>
        <behavior name="RestBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  
    <services>
      <service behaviorConfiguration="RestBehavior" name="Rest">
        <endpoint address="" binding="webHttpBinding" contract="IRest">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
      </service>
    </services>

  </system.serviceModel>


Calling Through direct Uri / Ajax request :

(Make Virtual directory in IIS named RestExample) 


<script type="text/javascript">
    function CallgetJSON() {
        $.getJSON("http://localhost/RestExample/RestSer.svc/FakeUrl/P1=Vivek",
        function(data) {
             alert(data);
         });
     }
</script>


Output:

Or Just Type your fake UriTemplate Url in browser address bar below is the result


Or You can use WebClient , WebRequest  and WebResponse Classes in asp.net C# for calling rest service through c# in server side.



Recent Article