代码之家  ›  专栏  ›  技术社区  ›  camainc

如何从2.0 asmx web服务返回JSON

  •  27
  • camainc  · 技术社区  · 17 年前

    电话如下:

          $(document).ready(function() {
             $.ajax({
                type: "POST",
                url: "DonationsService.asmx/GetDate",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                  // Hide the fake progress indicator graphic.
                  $('#RSSContent').removeClass('loading');
    
                  // Insert the returned HTML into the <div>.
                  $('#RSSContent').html(msg.d);
                }
              });
            });    
    

    POST /DonationsService.asmx/GetDate HTTP/1.1
    x-requested-with: XMLHttpRequest
    Accept-Language: en-us
    Referer: http://localhost:1238/text.htm
    Accept: application/json, text/javascript, */*
    Content-Type: application/json; charset=utf-8
    Accept-Encoding: gzip, deflate
    User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; eMusic DLM/4; .NET CLR 2.0.50727)
    Host: localhost:1238
    Content-Length: 2
    Connection: Keep-Alive
    Pragma: no-cache
    

    我尝试将contentType设置为“text/json”,并得到了相同的结果。

    以下是web服务方法:

    <WebMethod()> _
    Public Function GetDate() As String
    
        'just playing around with Newtonsoft.Json
        Dim sb As New StringBuilder
        Dim sw As New IO.StringWriter(sb)
        Dim strOut As String = String.Empty
    
        Using jw As New JsonTextWriter(sw)
            With jw
                .WriteStartObject()
                .WritePropertyName("DateTime")
                .WriteValue(DateTime.Now.ToString)
                .WriteEndObject()
            End With
            strOut = sw.ToString
        End Using
    
        Return strOut
    
    End Function
    

    这就是它的回报:

    <?xml version="1.0" encoding="utf-8"?>
    <string xmlns="http://DMS.Webservices.org/">{"DateTime":"11/13/2008 6:04:22 PM"}</string>
    

    当我请求Json时,有人知道如何强制web服务返回Json吗?

    请不要告诉我升级到.NETFramework3.5或诸如此类的东西(我没有那么愚蠢)。我需要一个2.0解决方案。

    7 回复  |  直到 12 年前
        1
  •  35
  •   Dave Ward    16 年前

    这没问题 return JSON from ASMX services in ASP.NET 2.0 . 您只需要安装ASP.NET AJAX扩展。

    一定要将[ScriptService]装饰添加到web服务中。这就是指示ASP.NET AJAX框架的服务器端部分为正确格式的请求返回JSON的原因。

    此外,如果您将“.d”与2.0一起使用,则需要从我的示例中的“msg.d”中删除“.d”。 The ".d" is a security feature that came with 3.5 .

        2
  •  12
  •   Tom    15 年前

    响应被包装在一个元素中,因为您的方法说它将返回一个字符串。您可以使用它来发送简单的json,但您的wsdl将被愚弄(函数是空的,但不响应数据)。

    [WebMethod(Description="return pure JSON")]
    public void retrieveByIdToPureJSON( int id )
    {
      Context.Response.Write( JsonConvert.SerializeObject( mydbtable.getById(id) );
    }
    

    祝你好运,汤姆

    顺便说一句:请参阅Newtonsoft.Json了解JsonConvert

        3
  •  10
  •   Darko    17 年前

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    

    其余的你都做对了:)

    Encosia 和 Andrew Roland's Blog

        4
  •  2
  •   Mark Cidade    17 年前

    在.NET2.0中,除了XML或二进制序列化之外,您可能无法执行任何操作。如果您没有使用自动生成的web引用,那么就不要使用ASMX。只需使用ASPX或ASHX即可。

        5
  •  2
  •   redsquare    17 年前

    Jayrock library Quick start for asp.net

    这允许您编写一个http处理程序来返回json。

    <%@ WebHandler Class="JayrockWeb.HelloWorld" %>
    
    namespace JayrockWeb
    {
        using System;
        using System.Web;
        using Jayrock.Json;
        using Jayrock.JsonRpc;
        using Jayrock.JsonRpc.Web;
    
        public class HelloWorld : JsonRpcHandler
        {
            [ JsonRpcMethod("greetings") ]
            public string Greetings()
            {
                return "Welcome to Jayrock!";
            }
        }
    }
    
        6
  •  1
  •   Seth    15 年前

    也可以使用Refelction编写自己的快速JSON转换器。

    Dim sb As New StringBuilder("{")
    For Each p As PropertyInfo In myObject.GetType().GetProperties()
        sb.Append(String.Format("""{0}"":""{1}"",", p.Name, p.GetValue(myObject,  
                  Nothing).ToString()))
    Next p
    
    //remove the last "," because it's uneeded.
    sb.Remove(sb.Length - 1, 1)
    
    sb.Append("}")    
    
        7
  •  0
  •   MW_dev    17 年前

    您需要覆盖Web服务的默认行为。我甚至不完全确定这是否可能。

    我知道这不是最有用的答案,但可能会让你朝着正确的方向前进。

    推荐文章