Wednesday, June 4, 2014

Cross Site Scripting in WCF Web Service. How to use AJAX in JavaScript to Get/Consume JSON from WCF in C#


WCF (Windows Communication Foundation) is a latest service oriented architecture. You can expose methods in WCF depend on the requirement. For example if we want to expose method which will return JSON data. then we need to mention this type of contract in method declaration. In this article I am focusing on exposing method which return string (JSON) and how a client can call this method from JavaScript (AJAX call using jQuery)

To expose a method in WCF as JSON we need to provide valid Contract:

[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string GetJSONData(string param1);

Above method accept one parameter "param1". WCF will expose this method to out side world and it can be used in AJAX call. This method can be consumed directly using query string also. If service url is:
https://MyServiceURL/Service.svc/json/
then we can call this method as:
https://MyServiceURL/Service.svc/json/GetJSONData?param1=123

AJAX call can also be setup easily with dataType as JSONP in case you are seeting up in cross domain. Jsonp is json with padding specially for cross domain request, if you are hosting a client application in different domain compare to service then you need to use datatype as JSONP in ajax request.

var ajaxRequest = $.ajax({
        type: "GET",
        url: https://MyServiceURL/Service.svc/json/GetJSONData?callback?",
        contentType: "application/json; charset=utf-8",
        dataType: "jsonp",
        data: { param1: "123" },
        success: function (oJSONObject) {
    // Your code here
 }