我创建了一个带有代码隐藏文件的ASMX文件。它工作得很好,但它正在输出XML。
但是,我需要它来输出JSON。ResponseFormat配置似乎不起作用。我的代码隐藏是:
[System.Web.Script.Services.ScriptService]
public class _default : System.Web.Services.WebService {
[WebMethod]
[ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
public string[] UserDetails()
{
return new string[] { "abc", "def" };
}
}
发布于 2012-11-22 19:32:47
要接收纯JSON字符串而不将其包装到XML中,必须将JSON字符串直接写入HttpResponse
,并将WebMethod
返回类型更改为void
。
[System.Web.Script.Services.ScriptService]
public class WebServiceClass : System.Web.Services.WebService {
[WebMethod]
public void WebMethodName()
{
HttpContext.Current.Response.Write("{property: value}");
}
}
发布于 2008-10-21 21:19:34
我花了4个小时在Google上学到了一个快速的陷阱,你可以在ASPX文件中使用PageMethods来返回一个静态方法的JSON (带有ScriptMethod()标记),但是如果你决定将你的静态方法转移到asmx文件,它就不能是一个静态方法。
此外,您还需要告诉web服务Content-Type: application/json,以便从调用中返回JSON (我使用的是jQuery,3 Mistakes To Avoid When Using jQuery的文章非常有启发性-它来自另一个答案中提到的同一网站)。
发布于 2008-10-17 10:38:54
您是从客户端脚本还是在服务器端调用web服务?
您可能会发现向服务器发送内容类型标头会有所帮助,例如
‘'application/json;charset=utf-8’
在客户端,我使用prototype客户端库,在进行Ajax调用时有一个contentType参数,您可以在其中指定该参数。我认为jQuery有一个getJSON方法。
https://stackoverflow.com/questions/211348
复制相似问题