WebMethod总是返回XML吗?

Nic*_*ckz 0 asp.net web-services

ASP.NET [WebMethod],它总是返回XML吗?

我知道它只能返回可序列化的数据类型,但是它可以返回一个JSON吗?

Bru*_*oLM 7

我知道,您可以返回XML或JSON.

要返回JSON,请添加此注释或方法:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Run Code Online (Sandbox Code Playgroud)

在你的课上允许 ScriptService

[ScriptService]
Run Code Online (Sandbox Code Playgroud)

一个例子:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Dictionary<string, object> Test()
{
    var ret = new Dictionary<string, object>();
    ret.Add("Test", 1);
    return ret;
}

// result:
{d:{Test:1}}
Run Code Online (Sandbox Code Playgroud)