WS应该只返回JSON而不是XML包装的JSON

时间:2015-02-03 01:51:40

标签: c# json web-services

我有一个WS应该只返回JSON,但是它被包装在XML中。 已经删除了

[WebService(Namespace = "http://www.url.com/")]

但它没有任何影响,我的WS看起来像这样

[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 pointer : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public string HelloWorld(string name)
    {
        Account account = new Account
        {
            Email = "james@example.com",
            Active = true,
            CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
            Roles = new List<string>
              {
                "User",
                "Admin"
              }
        };
        return JsonConvert.SerializeObject(account, Formatting.Indented);
        //return "Hello World";
    }

回报如下:

此XML文件似乎没有与之关联的任何样式信息。文档树如下所示。

<string xmlns="http://tempuri.org/">
{ "Email": "james@example.com", "Active": true, "CreatedDate": "2013-01-20T00:00:00Z", "Roles": [ "User", "Admin" ] }
</string>

我的配置如下所示:

<configuration>
<system.web.extensions>
    <scripting>
        <webServices>
            <jsonSerialization maxJsonLength="500000000"/>
        </webServices>
    </scripting>
</system.web.extensions>
<system.webServer>
    <handlers>
        <add name="ScriptHandlerFactory"
             verb="*" path="*.asmx"
             type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
             resourceType="Unspecified" />
    </handlers>
</system.webServer>
<system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime targetFramework="4.0" />
</system.web>
<system.webServer>
    <defaultDocument enabled="true">
        <files>
            <clear />
            <add value="pointer.asmx" />
            <add value="default.aspx" />
        </files>
    </defaultDocument>
    <security>
        <authorization>
            <add accessType="Allow" users="?" />
        </authorization>
    </security>
    <httpErrors errorMode="Detailed" />
    <!--<handlers accessPolicy="Read, Execute, Script" />-->
</system.webServer>

无论如何都要保持包装器并且只返回JSON?

1 个答案:

答案 0 :(得分:0)

ScriptService会自动将结果序列化为JSON,您不必手动执行,否则会被序列化两次。我认为客户端的内容类型是指定application / xml而不是application / json?