1

I have a pretty basic ScriptMethod:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetData(string token)
{
    Context.Response.ContentType = "text/json";
    Context.Response.Clear();
    Context.Response.BufferOutput = true;

    List<string> data = new List<string>() { "foo", "bar", "foobar" };

    using (var stream = new StreamWriter(Context.Response.OutputStream))
    {
        JsonSerializer.Create().Serialize(stream, data);
    }

    Context.Response.OutputStream.Flush();
}

If I hit this API via a GET, I receive an acceptable response:

["foo","bar","foobar"]

If I hit this API via a POST, instead, I receive a malformed response:

["foo","bar","foobar"]{"d":null}

How can I make this function write the response, without appending the d object?

Collin Dauphinee
  • 13,664
  • 1
  • 40
  • 71

1 Answers1

1

You don't don't have to handle the serialization yourself, let the framework do that for you.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<string> GetData(string token)
{
    return new List<string>() { "foo", "bar", "foobar" };
}

I think what you'll get back is d[ [ "foo", "bar", "foobar" ] ] but at least it's valid. The d[] construct is a security thing.

lincolnk
  • 11,218
  • 4
  • 40
  • 61
  • In the actual case, I'm using JSON.net to make complex transformations to the actual C# objects being sent in the response. This makes returning objects unfeasible, unless there's a way to have ASP.NET serialize with JSON.net and various custom resolvers/serializers. – Collin Dauphinee Apr 15 '15 at 23:09
  • maybe serialize everything to a `string` and return that, rather than writing directly to the stream. it'll still be wrapped in `d[]` but won't be mangled. – lincolnk Apr 15 '15 at 23:11
  • That's currently what I'm doing, but it's not ideal. – Collin Dauphinee Apr 15 '15 at 23:11
  • to do any better than that you'll probably have to roll your own request handler. – lincolnk Apr 15 '15 at 23:13