Sunday 19 April 2015

Today we will learn how to call .asmx web service which is hosted in different domain through jquery ajax code written in web page in different domain (Cross domain calling)


1) open visual studio -> Web -> ASP.NET Empty Webapplication ->name it "mySampleProject"






2) right click "mySampleProject" and click Add->New Items-> WebService->name it "SampleService.asmx".


3) click your newly created webservice and uncomment the below code written above class


[System.Web.Script.Services.ScriptService]


4) Put Below code on top of your method. Before this add "using System.Web.Services;" at the top


 [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]


5) Your code should look like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;

namespace mySampleProject
{
    /// <summary>
    /// Summary description for SampleService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [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]
    public class SampleService : System.Web.Services.WebService
    {

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
        public void HelloWorld(string callback)
        {
            string str = "Hello World";
            // <code here to populate list on line above>

            // Method 1: use built-in serializer:
            StringBuilder sb = new StringBuilder();
            JavaScriptSerializer js = new JavaScriptSerializer();
            sb.Append(callback + "(");
            sb.Append(js.Serialize(str));
            sb.Append(");"); 

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

6) open your web.config file and add below code Under <system.web>  </system.web> tag 


<webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>

otherwise if you will not add this then you will recieve following error 
"Request format is unrecognized for URL unexpectedly ending"


Note: 

Default code->

 public string HelloWorld()
        {
            return "Hello World";
        }

this code will return data in the form of xml and you will recieve `following error->
"Unexpected token <   Resource interpreted as Script but transferred with MIME type text/xml"
. So make sure you return data in the jsonp format otherwise you will not get the result.
We have to go to Jsonp because for cross domain call we have no other way. so the data returned by method should be in jsonp format.

Changed funciton code

 public void HelloWorld(string callback)
        {
            string str = "Hello World";
            // <code here to populate list on line above>

            // Method 1: use built-in serializer:
            StringBuilder sb = new StringBuilder();
            JavaScriptSerializer js = new JavaScriptSerializer();
            sb.Append(callback + "(");
            sb.Append(js.Serialize(str));
            sb.Append(");"); 

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

This code will always return data in jsonp format.


7) Now your web service is ready with HelloWorld Method do ctrl+f5 and it will be hosted in local host.

CALLING THIS WEBSERVICE USING AJAX 

1) Create another empty asp.net application as explained above.
2) add a webform to this project.
3)Add below code to your Web form under <script></script> tag.

$(document).ready(function () {
         
               $.ajax({
                    type: "GET",
                    url: "http://localhost:17370/SampleService.asmx/HelloWorld",
                    data: "{}",
                    crossDomain: true,
                    contentType: "application/json; charset=utf-8",
                    dataType: "jsonp",
                   async:false,
                    success:function(data,status){
                        alert(data);

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert("Error Occured!" + " | " + XMLHttpRequest + " | " + textStatus + " | " +
                        errorThrown);
                    }
                });

                
        });

URL of  my service : "http://localhost:17370/SampleService.asmx/HelloWorld"


you will recieve an alert with "Hello World".


NOTE:-- Even you can host this web service in "windows azure" application and access it through above ajax code. Remember your method should return jsonp format not xml.