0

I'm trying to create a simple as possible web service with a single method that will return a proper JSON. Please, help me make this work instead of proposing WCF, MVC or other alternatives.
I'm aware of a possibility to write a manually serialized via JavaScriptSerializer(or other helpers and frameworks such as DataContractJsonSerializer or Json.NET) object directly to the Response. But as far as I understand the framework can do all the work by itself, and I just can't find the proper way of using it.
I've uncommented the ScriptServiceAttribute, and it seems that framework does it's job, but I get the JSON string with escaped quotes, and as result it cannot be evaluated into a usable object.
I understood that adding the ScriptMethodAttribute and specifying ResponseFormat = ResponseFormat.Json to the method declaration is redundant, since it's set so by default for ScriptServiceAttribute, anyway adding it didn't help.
I've also tried to specify the return type as object and IEnumerable<object> but it didn't help either: casting to an object made the method unusable via standard browser test execution(by opening the URL of the service and launching the method) - the following error was returned

"System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] may not be used in this context."

while the later casting made the whole web service unusable with following error being generated

"Cannot serialize interface System.Collections.Generic.IEnumerable`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]."  

Here are my steps:

  1. File > New > Project : Installed > Templates > Visual C# > Web > ASP.NET Empty Web Application
  2. Solution Explorer > Context Menu of the project from Step 1 > Add > New Item > Installed > Visual C# > Web > Web Service

Here the code of my aspx.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace PlayGround
{
    /// <summary>
    /// Summary description for Example
    /// </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 Example : System.Web.Services.WebService
    {

        [WebMethod]
        public List<String> HelloWorld()
        {
            List<String> s = new List<string>();
            s.Add("q");
            s.Add("a");
            s.Add("z");
            return s;
        }
    }
}

Bellow is the content of web.config:

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.0" />
    </system.web>

</configuration>

Here is my test page JavaScript, again as simple as possible no jQuery, no nothing, just pure AJAX and synchronous execution:

<script type="text/javascript">
   var jsO = null;
   var request = new XMLHttpRequest();

   request.open('Get', 'http://localhost:57560/Example.asmx?op=HelloWorld', false);
   request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   request.send(null);

   if ((request.readyState == 4) && (request.status == 200)) // Completed operation 
   {
       request.open("POST","http://localhost:57560/Example.asmx/HelloWorld", false);
       request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
       request.setRequestHeader("Accept", "application/json");

       try
       {
           request.send();
       }
       catch (e)
       {
           console.log(e);
       }

       jsO = eval(request.responseText); // Error: request.responseText = "{\"d\":[\"q\",\"a\",\"z\"]}"
   }
</script>
leppie
  • 115,091
  • 17
  • 196
  • 297
Jyrkka
  • 526
  • 1
  • 8
  • 26

2 Answers2

0

change

jsO = eval(request.responseText); 

to

jsO = eval("(" + request.responseText + ")");

see this prior question

Parsing JSON from XmlHttpRequest.responseJSON

Community
  • 1
  • 1
Eric Carlson
  • 761
  • 1
  • 6
  • 11
  • What are these parentheses do? – Jyrkka Dec 01 '14 at 09:32
  • It turns it into an expression instead of trying to interpret it as a code block. See the following for an explanation. But as you've already figured out JSON.parse is better. http://stackoverflow.com/questions/964397/why-does-javascripts-eval-need-parentheses-to-eval-json-data – Eric Carlson Dec 01 '14 at 13:15
0
jsO = eval(request.responseText); 

could be changed to:

jsO = JSON.parse(request.responseText);
Jyrkka
  • 526
  • 1
  • 8
  • 26