Friday, August 8, 2014

Simple WCF Application Call From Client End

Today, i am going to create simple WCF Web Service and consume same web service from client side.
(A) Steps to create new WCF Service
(1) Right Click on your solution --> Add --> New Project --> Select ASP.NET Web Application --> Give appropriate name like "REST"
(2) Above step will create new Web Application, you can remove master page and other pages included from newly created project
(3) Right Click on newly created project --> Add --> New Item --> Select "WCF Service" --> Give appropriate name like "MyService"
(4) Above step will add an interface named "IMyService" already implemented and one service with extension "MyService.svc"
(5) Remove existing code implemented in interface as well as in service.
(6) Add following line of code in interface
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
string DoWorkWithString();
- This is simple method we have declare which will return string on execute.
- WebInvoke requires "System.ServiceModel.Web" name space to be added as reference in your project
(7) Implement above method with following code in MyService.cs
public string DoWorkWithString()
{
    return "This is one test";
}

(8) After completion of above code, create virtual directory named "REST" and bind it with above project.

(9) To run with existing code from client end, you need to change serviceModel tag with following line of code in your Web.Config file. To do that, replace following line of code of serviceModel with your Web.Config tag.



(B) Steps to call WCF Service from client end
Now, you are done with your simple service implementation, you can now call above service from client end using following line of code to your html and it will prompt "This is one test".
$.ajax({
    url: 'http://localhost/REST/MyService.svc/DoWorkWithString',
    dataType: 'json',
    cache: false,
    type: 'GET',
    contentType: 'application/json; charset=utf-8',
    data: {},
    error: function (XMLHttpRequest, textStatus, errorThrown) {
     alert('Error occurred during operation');
    },
    success: function (data1) {
        alert(data1.DoWorkWithStringResult);
    }
});

(C) You can also following navigate to following links to do same.


(1) An Introduction to WCF

(2) Four Steps to Create First WCF Service For Beginners

(3) Consuming WCF / ASMX / REST service using JQuery
       

No comments:

Post a Comment