我创建了一个带有代码隐藏文件的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" };
}
}
Run Code Online (Sandbox Code Playgroud)
小智 53
要接收纯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}");
}
}
Run Code Online (Sandbox Code Playgroud)
Pav*_*uva 39
从 WebService的返回XML即使ResponseFormat设置为JSON:
确保请求是POST请求,而不是GET.Scott Guthrie有一篇文章解释了原因.
虽然它是专门为jQuery编写的,但这对您也很有用:
使用jQuery来使用ASP.NET JSON Web服务
mar*_*arc 15
这可能是现在的老消息,但魔术似乎是:
有了这些部分,GET请求就会成功.
对于HTTP POST
在客户端(假设您的webmethod被称为MethodName,它需要一个名为searchString的参数):
$.ajax({
url: "MyWebService.asmx/MethodName",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ searchString: q }),
success: function (response) {
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ": " + jqXHR.responseText);
}
});
Run Code Online (Sandbox Code Playgroud)