【问题标题】:how to get only json data with webservice如何使用 webservice 仅获取 json 数据
【发布时间】: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


【解决方案1】:

你应该使用以下,不要手动序列化,只需执行以下操作

[WebService(Namespace = "http://example.com/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]System.Web.Services.WebService
[ScriptService]
public class services :WebService  
{    
    [WebMethod(CacheDuration = 60)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<TestObject> GetObjectCollection()
    {
           return YourService.GetObjectCollection().ToList();
    }
}

参考:getting-json-data-using-an-asmx-web-servicehere

【讨论】:

  • 是的,它与link合作
  • @deepak 我对该解决方案投了反对票,并留下了评论原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
  • 2015-01-05
  • 2023-04-01
  • 1970-01-01
  • 2017-03-26
相关资源
最近更新 更多