1

Why does the Web Service call fail? On a button click, a web service is called from a asp.net page using jquery. The web servcie returns a JSON string: {"Message":"Hello World"}. I'm not trying to do anything with the returned message at this time. I'm simply trying to call the web service without falling through the error function. Please see below for the code:

The Web service:  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Runtime.Serialization.Json;

namespace EForm.Services
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class PeopleWebService : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void HelloWorld()
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var jsonData = new
            {
                Message = "Hello World"
            };
            string retJSON = js.Serialize(jsonData);
            Context.Response.Write(retJSON);
        }
    }
}

The asp.net page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.7-vsdoc.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
<script type="text/javascript">
    function getUserName() {
        $.ajax({
            url: "http://localhost:1211/Services/PeopleWebService.asmx/HelloWorld",
            cache: false, // don't cache results
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{}",
            success: function () {
                alert("worked");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("Status: " + xhr.status);
                alert("Response Text: " + xhr.responseText);
                alert("Thrown Error: " + thrownError);
            }
        });
        return false;
    }
    $(document).ready(function () {
        $("#Search").click(getUserName);
    });
</script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:Button ID="Search" runat="server" Text="Search" />
    </form>
</body>
</html>

The Return Errors
FireFox 24.0
    Status: 0
    Response Text:
    Thrown Error:

Opera 17.0
    Status: 0
    Response Text:
    Thrown Error:

Chrome 30.0.1599.69 m
    Status: 0
    Response Text:
    Thrown Error:

IE 10
    Status: 200
    Response Text: {"Message":"Hello World"}{"d":null}
    Thrown Error:  SyntaxError: Syntax error
1
  • I have never seen a web service constructed as yours above. I have seen them as as method returning a string. Commented Oct 17, 2013 at 18:33

2 Answers 2

1

You're actually doing more than necessary, the ASP.NET service model is perfectly capable of serializing response itself. By manually writing to the response stream you're essentially "double-dipping" into the response stream. First, you've written your own JSON data {"Message":"Hello World"}, but then the pipeline is also appending its own null JSON serialized object {"d":null} (since your method is returning void/null).

The browser is then receiving invalid JSON: {"Message":"Hello World"}{"d":null}, which it will respond to in a variety of ways depending on the browser implementation (as you've seen).

Instead, just let ASP.NET handle the serialization for you:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public dynamic HelloWorld()
{
    return new
    {
        Message = "Hello World"
    };
}

Which will give a (valid) response of {"d":{"Message":"Hello World"}}

Sign up to request clarification or add additional context in comments.

2 Comments

This gets me 90% of the way there. Just a few follow up questions to complete the answer: 1. I now get an error about not being able to serialize because of a missing parameterless constructor. Can I send a string back like this or must it be an object? 2. What is the purpose of the dynamic return type?
Nevermind. Only get this error when envoking the service from a web browser. I suppose the default return type there is XML. When I envoke the service from my client (and specify the JSON return type) it works just fine. Yeah, now I can move onward!!! Thanks all that made an effort to answer this!
0

Try having your method return the data instead of writing it to the Response:

    [WebMethod]
    public string HelloWorld()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        var jsonData = new
        {
            Message = "Hello World"
        };
        return js.Serialize(jsonData);            
    }

1 Comment

This causes the response to return SOAP/XML. <?xml version="1.0" encoding="UTF-8"?> <string xmlns="tempuri.org">{"Message":"Hello World"}</string>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.