1

我有一个非常基本的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();
}

如果我通过 GET 访问此 API,我会收到可接受的响应:

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

相反,如果我通过 POST 访问此 API,则会收到格式错误的响应:

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

我怎样才能让这个函数写响应,而不附加d对象?

4

1 回答 1

1

您不必自己处理序列化,让框架为您完成。

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

我认为你会得到的是d[ [ "foo", "bar", "foobar" ] ],但至少它是有效的。构造d[]是一个安全的东西。

于 2015-04-15T22:59:07.977 回答