C# asp.net webservices-如何在与“Web服务”相同的级别上返回参数;d";

C# asp.net webservices-如何在与“Web服务”相同的级别上返回参数;d";,c#,asp.net,json,web-services,C#,Asp.net,Json,Web Services,自.NET3.5以来,返回json的web服务将数据包装在名为“d”的参数中。我所描述的特性在其他地方都有记录 我想知道是否有一种方法可以向json添加一个与“d”级别相同的参数 借用上面的例子,如果我的一个web服务的输出是 {"d":{"__type" : "Person", "FirstName" : "Dave", "LastName" : "Ward"}} 我想要的是 {"d":{"__type" : "Person", "First

自.NET3.5以来,返回json的web服务将数据包装在名为“d”的参数中。我所描述的特性在其他地方都有记录

我想知道是否有一种方法可以向json添加一个与“d”级别相同的参数

借用上面的例子,如果我的一个web服务的输出是

{"d":{"__type"    : "Person",
      "FirstName" : "Dave",
      "LastName"  : "Ward"}}
我想要的是

{"d":{"__type"    : "Person",
      "FirstName" : "Dave",
      "LastName"  : "Ward"},
 "z":{"__type"    : "AnotherType",
      "Property"  : "Value"}}

有办法做到这一点吗?

我认为没有办法。web服务函数正在返回对象类型。即使您尝试让它返回Object()is,它也将执行is{“d”:[Object 1…,Object 2…]}


如果您确实需要特定的输出格式,您可以编写一个通用处理程序,让ashx页面以您想要的特定格式返回json。

,但无论如何都不建议这样做。JSON结果被包装为安全特性

但是,如果您确实需要,这里有一个解决方案:

[WebMethod]
中,您需要修改添加的元素

        Context.Response.ClearContent();
        Context.Response.Filter = new JsonHackFilter(Context.Response.Filter);
其中
JsonHackFilter

class JsonHackFilter : MemoryStream
{
    private readonly Stream _outputStream = null;

    public JsonHackFilter(Stream output)
    {
        _outputStream = output;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {

        string bufferContent = Encoding.UTF8.GetString(buffer);

        // TODO: Manually manipulate the string here

        _outputStream.Write(Encoding.UTF8.GetBytes(bufferContent), offset,
                           Encoding.UTF8.GetByteCount(bufferContent));

        base.Write(buffer, offset, count);
    }       

}