1

I'm trying to understand cross domain calls to a web-service from jQuery ajax. I have a web-service running in one project and a simple ASP.NET web application in another.

Web Service code -

    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public string HelloWorld()
    {
        string json = "Hello World";

        string jsoncallback = HttpContext.Current.Request["callback"];
        if (string.IsNullOrWhiteSpace(jsoncallback))
        {
            return json;
        }
        else
        {
            return string.Format("{0}({1})", jsoncallback, json);
        }

    }

Call to the web service from a page -

    $(function () {
        $("#btnCall").click(function () {
            var urlToCall = "http://localhost:55172/SampleWebService.asmx/HelloWorld";
            $.ajax({
                url: urlToCall,
                type: "GET",
                dataType: "jsonp",
                contentType: "application/javascript",
                jsonpCallback: "MyFunc",
                error: function () {
                    console.log("Error!");
                },
                success: function () {
                    console.log("Success!!");
                }
            });
            return false;
        });
        function MyFunc() {
            console.log("Callback fired!");
        }
    });

As you can see I'm calling the webservice on a button click. But this call fails saying,

Request format is unrecognized for URL unexpectedly ending in '/HelloWorld'. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: Request format is unrecognized for URL unexpectedly ending in '/HelloWorld'.

This is rectified if I add the following to my web.config -

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

But if I do that, no matter what I do, my data is always returned in an XML format. I need the data in a valid JSON format, what do I do?

Also note that I'm able to call this webservice from a aspx page in the same project, and that seems to be working just fine.

Abijeet Patro
  • 2,684
  • 2
  • 33
  • 62

1 Answers1

1

You need to serialize service output using custom code. These links can help you:

Community
  • 1
  • 1
Egor4eg
  • 2,660
  • 1
  • 19
  • 41