【发布时间】:2016-06-19 01:50:43
【问题描述】:
我已经创建了网络服务:
demo.asmx
<%@ WebService Language="C#" CodeBehind="~/App_Code/demo.cs" Class="demo" %>
demo.cs
public class demo : System.Web.Services.WebService
{
public demo()
{
}
[WebMethod]
[ScriptMethod(UseHttpGet = true, XmlSerializeString = false, ResponseFormat = ResponseFormat.Json)]
public string saveUserData()
{
Employee[] emps = new Employee[] {
new Employee()
{
Id=1,
Name="xyz"
},
new Employee()
{
Id=2,
Name="abc"
}
};
return new JavaScriptSerializer().Serialize(emps);
}
}
现在当我运行它时,它会给我以下数据:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<string>[{"Id":1,"Name":"xyz"},{"Id":2,"Name":"abc"}]</string>
所以我检查了控制台,它给了我
Cache-Control → private, max-age=0
Content-Encoding → gzip
Content-Length → 232
Content-Type → text/xml; charset=utf-8
Date → Sat, 05 Mar 2016 06:33:53 GMT
Server → Microsoft-IIS/8.0
Vary → Accept-Encoding
X-AspNet-Version → 4.0.30319
X-Powered-By → ASP.NET
X-SourceFiles → =?UTF-8?B?RDpcRGVtb193ZWJz
它给出的内容类型是text/xml,即使我已经定义了 Json 响应格式。
我怎样才能得到像下面这样的只有 json 响应?
[{"Id":1,"Name":"xyz"},{"Id":2,"Name":"abc"}]
【问题讨论】:
-
您不会在 Web 服务中手动序列化为 JSON。您返回对象本身,服务将其序列化为正确的类型。除此之外,-
-
@GSerg 我没有在 aspx 页面中使用任何
ajax。此应用程序不包含 aspx 页面。我只是创建网络服务而已。 -
是否使用 ajax 并不重要。你提供correct content-type吗?
-
@GSerg 我只有这种困惑。如何传递内容类型?因为我只是点击了像 -
http://localhost:2079/demo.asmx/saveUserData这样的网址。那么我必须在哪里定义content type?
标签: c# asp.net json web-services asmx