如何让一个ASMX文件输出JSON [英] How to let an ASMX file output JSON
问题描述
我创建了身后文件code的ASMX文件。它的工作很好,但它正在输出XML。
不过,我需要它输出JSON。该ResponseFormat配置似乎并没有工作。我的code-背后是:
[System.Web.Script.Services.ScriptService]
公共类_default:System.Web.Services.WebService {
[的WebMethod]
[ScriptMethod(UseHttpGet = TRUE,ResponseFormat = ResponseFormat.Json)
公共字符串[]的UserDetails()
{
返回新的字符串[] {ABC,高清};
}
}
返回即使ResponseFormat设置为XML JSON :
确认该请求是一个POST请求,而不是GET。斯科特格思里有一个<一个href=\"http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx\">post解释为什么。
虽然它的jQuery编写的,这也可能对你有用:
<一href=\"http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/\">http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
块引用>I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.
However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:
[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" }; } }
解决方案From WebService returns XML even when ResponseFormat set to JSON:
Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.
Though it's written specifically for jQuery, this may also be useful to you:
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
这篇关于如何让一个ASMX文件输出JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!