Wednesday, April 6, 2016

How to consume cross site asmx returned Json service with Javascript

Hi There,

If you are trying to access a web service which is hosted on other domain or port or outside the network, you need to use jsonp instead of json. After spending hours, finally i found a solution on stackoverflow ( the only friend site of developers :o)  Thanks to NickG for writing this answer). You can read the inside story of this issue on the actual question on stackoverflow. I am posting here the direct code which worked for me. Hope you get some clue from here.

Javascript / Jquery Code:

        $.ajax({
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            url: "http://localhost:8080/Service.asmx/MyCustomMethodName",
            data: { User: 'Admin', Mon: 8}, // example of parameter being passed
            dataType: "jsonp",
            success: onDataReceived
        });

        function onDataReceived(data) {
            alert("Hi " + data.UserName + " Its " + data.Month + " of this year.");
        }


C# Employee Class:

    public class Employee
    {
        public string UserName { get; set; }
        public int Month { get; set; }

    }  


Service.asmx Class:

 /// <summary>
    /// Summary description for Service
    /// </summary>
    [WebService(Namespace = "http://contoso.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    [ScriptService]
    public class Service : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void MyCustomMethodName(string User, int Mon, string callback)
        {
            Employee emp = new Employee();
            emp.UserName = User;
            emp.Month = Mon;
            StringBuilder sb = new StringBuilder();
            JavaScriptSerializer js = new JavaScriptSerializer();
            sb.Append(callback + "(");
            sb.Append(js.Serialize(emp));
            sb.Append(");");

            Context.Response.Clear();
            Context.Response.ContentType = "application/json";
            Context.Response.Write(sb.ToString());
            Context.Response.End();
        }
    }

As described in this article, the "string callback" in the above method is the default query string parameter that Jquery passes itself. If you want to see what is passing in it, use chrome, press F12 and see in request headers. This example worked for me perfectly.

Hope it helps someone.


No comments:

Post a Comment