Skip to main content

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.



Popular posts from this blog

Uploading large file in chunks in Asp.net Mvc c# from Javascript ajax

Often we have a requirement to upload files in Asp.net, Mvc c# application but when it comes to uploading larger file, we always think how to do it as uploading large file in one go have many challenges like UI responsiveness, If network fluctuate for a moment in between then uploading task get breaks and user have to upload it again etc.

Regular expression for alphanumeric with space in asp.net c#

How to validate that string contains only alphanumeric value with some spacial character and with whitespace and how to validate that user can only input alphanumeric with given special character or space in a textbox (like name fields or remarks fields). In remarks fields we don't want that user can enter anything, user can only able to enter alphanumeric with white space and some spacial character like -,. etc if you allow. Some of regular expression given below for validating alphanumeric value only, alphanumeric with whitspace only and alphanumeric with whitespace and some special characters.

How to handle click event of linkbutton inside gridview

Recently I have posted how to sort only current page of gridview , Scrollble gridview with fixed header through javascript , File upload control inside gridview during postback and now i am going to explain how to handle click event of linkbutton or any button type control inside gridview. We can handle click event of any button type control inside gridview by two way first is through event bubbling and second one is directly (in this type of event handling we need to access current girdviewrow container)

regex - check if a string contains only alphabets c#

How to validate that input string contains only alphabets, validating that textbox contains only alphabets (letter), so here is some of the ways for doing such task. char have a property named isLetter which is for checking if character is a letter or not, or you can check by the regular expression  or you can validate your textbox through regular expression validator in asp.net. Following code demonstrating the various ways of implementation.