C# 如何让 ASMX 文件输出 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/211348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to let an ASMX file output JSON
提问by doekman
I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.
我创建了一个带有代码隐藏文件的 ASMX 文件。它工作正常,但它正在输出 XML。
However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:
但是,我需要它来输出 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" };
}
}
采纳答案by Pavel Chuchuva
From WebService returns XML even when ResponseFormat set to JSON:
从 WebService的返回XML即使ResponseFormat设置为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:
Using jQuery to Consume ASP.NET JSON Web Services
确保请求是 POST 请求,而不是 GET。Scott Guthrie 有一篇文章解释了原因。
虽然它是专门为 jQuery 编写的,但它也可能对您有用:
Using jQuery to Consume ASP.NET JSON Web Services
回答by bitsprint
Are you calling the web service from client script or on the server side?
您是从客户端脚本还是在服务器端调用 Web 服务?
You may find sending a content type header to the server will help, e.g.
您可能会发现向服务器发送内容类型标头会有所帮助,例如
'application/json; charset=utf-8'
'应用程序/json; 字符集=utf-8'
On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.
在客户端,我使用原型客户端库,并且在进行 Ajax 调用时有一个 contentType 参数,您可以在其中指定它。我认为 jQuery 有一个 getJSON 方法。
回答by Bryan Rehbein
A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.
我通过艰难的方式(基本上在 Google 上花费了 4 个小时)学习了一个快速的问题,您可以在 ASPX 文件中使用 PageMethods 为静态方法返回 JSON(带有 [ScriptMethod()] 标记),但是如果您决定移动您的静态方法到 asmx 文件,它不能是静态方法。
Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQueryarticle was very enlightening - its from the same website mentioned in another answer here).
此外,您需要告诉 Web 服务 Content-Type: application/json 以便从调用中获取 JSON(我正在使用 jQuery 并且使用 jQuery 时要避免的3 个错误文章非常有启发性 - 它来自同一个网站在这里的另一个答案中提到)。
回答by marc
This is probably old news by now, but the magic seems to be:
这可能是旧消息了,但神奇之处似乎是:
- [ScriptService] attribute on web service class
- [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] on method
- Content-type: application/json in request
- Web 服务类的 [ScriptService] 属性
- [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 关于方法
- 内容类型:请求中的应用程序/json
With those pieces in place, a GET request is successful.
有了这些部分,GET 请求就成功了。
For a HTTP POST
对于 HTTP POST
- [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] on method
- [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] 关于方法
and on the client side (assuming your webmethod is called MethodName, and it takes a single parameter called searchString):
在客户端(假设您的 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);
}
});
回答by Kevin
Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.
替代方案:使用通用 HTTP 处理程序 (.ashx) 并使用您最喜欢的 json 库来手动序列化和反序列化您的 JSON。
I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.
我发现对请求处理和生成响应的完全控制胜过 .NET 为简单的 RESTful Web 服务提供的任何其他服务。
回答by iCorrect
To receive a pure JSON string, without it being wrapped into an XML, you have to write the JSON string directly to the HttpResponse
and change the WebMethod
return type to void
.
要接收纯 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}");
}
}