我有以下测试方法:
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<System.Web.Script.Services.ScriptService()> _
Public Class DemoService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetCustomer() As String
Return "Microsoft"
End Function
End Class
即使添加了 ResponseFormat 属性,响应仍以 XML 而不是 JSON 的形式返回。
感谢您的想法。
最佳答案
我问这个问题有点晚了,但希望这能帮助你或其他后来偶然发现这个话题的人。
你绝对可以 use ASMX services to communicate in JSON .
您的服务代码看起来没问题。既然你没有展示你是如何调用它的,我敢打赌这就是你的问题所在。从 ASMX“ScriptServices”中获取 JSON 的一项要求是您必须使用正确的内容类型 header 调用它们,并且必须使用 POST 请求。 Scott Guthrie 有一篇关于 the reasoning behind those requirements 的好文章.
因此,如果您只是在浏览器中请求 DemoService.asmx/GetCustomer
,您将获得 XML。但是,如果您使用 application/json
内容类型发出 POST 请求,您将获得与 JSON 序列化相同的结果。
如果您使用的是 jQuery,下面是您将如何在客户端请求 DemoService 的示例:
$.ajax({
type: "POST",
contentType: "application/json",
url: "DemoService.asmx/GetCustomer",
data: "{}",
dataType: "json",
success: function(response) {
// Prints your "Microsoft" response to the browser console.
console.log(response.d);
}
});
更多信息:http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
关于javascript - 如何从 ASP.NET .asmx 返回 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1678101/