【问题标题】:JSON Web ServiceJSON网络服务
【发布时间】:2013-10-17 18:29:09
【问题描述】:

为什么 Web 服务调用失败? 单击按钮时,使用 jquery 从 asp.net 页面调用 Web 服务。 Web 服务返回一个 JSON 字符串:{"Message":"Hello World"}。我现在不想对返回的消息做任何事情。我只是试图调用 Web 服务而不会通过错误函数。代码见下:

The Web service:  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Runtime.Serialization.Json;

namespace EForm.Services
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class PeopleWebService : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void HelloWorld()
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            var jsonData = new
            {
                Message = "Hello World"
            };
            string retJSON = js.Serialize(jsonData);
            Context.Response.Write(retJSON);
        }
    }
}

The asp.net page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.7-vsdoc.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
<script type="text/javascript">
    function getUserName() {
        $.ajax({
            url: "http://localhost:1211/Services/PeopleWebService.asmx/HelloWorld",
            cache: false, // don't cache results
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{}",
            success: function () {
                alert("worked");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("Status: " + xhr.status);
                alert("Response Text: " + xhr.responseText);
                alert("Thrown Error: " + thrownError);
            }
        });
        return false;
    }
    $(document).ready(function () {
        $("#Search").click(getUserName);
    });
</script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:Button ID="Search" runat="server" Text="Search" />
    </form>
</body>
</html>

The Return Errors
FireFox 24.0
    Status: 0
    Response Text:
    Thrown Error:

Opera 17.0
    Status: 0
    Response Text:
    Thrown Error:

Chrome 30.0.1599.69 m
    Status: 0
    Response Text:
    Thrown Error:

IE 10
    Status: 200
    Response Text: {"Message":"Hello World"}{"d":null}
    Thrown Error:  SyntaxError: Syntax error

【问题讨论】:

  • 我从未见过像您上面那样构建的 Web 服务。我将它们视为返回字符串的方法。

标签: jquery asp.net json web-services


【解决方案1】:

实际上,您所做的超出了必要的范围,ASP.NET 服务模型完全能够序列化响应本身。通过手动写入响应流,您实际上是在“双重浸入”响应流。首先,您已经编写了自己的 JSON 数据 {"Message":"Hello World"},但随后管道还附加了自己的空 JSON 序列化对象 {"d":null}(因为您的方法返回 void/null)。

然后浏览器接收到无效的 JSON:{"Message":"Hello World"}{"d":null},它会根据浏览器的实现以多种方式响应(如您所见)。

相反,让 ASP.NET 为您处理序列化:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public dynamic HelloWorld()
{
    return new
    {
        Message = "Hello World"
    };
}

这将给出{"d":{"Message":"Hello World"}}的(有效)响应

【讨论】:

  • 这让我走完了 90% 的路。只需几个后续问题即可完成答案: 1. 我现在收到一个关于由于缺少无参数构造函数而无法序列化的错误。我可以像这样发回一个字符串还是必须是一个对象? 2.动态返回类型的目的是什么?
  • 没关系。只有在从 Web 浏览器调用服务时才会出现此错误。我想默认的返回类型是 XML。当我从客户端调用服务(并指定 JSON 返回类型)时,它工作得很好。是的,现在我可以继续前进了!!!感谢所有努力回答这个问题的人!
【解决方案2】:

尝试让您的方法返回数据,而不是将其写入Response

    [WebMethod]
    public string HelloWorld()
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        var jsonData = new
        {
            Message = "Hello World"
        };
        return js.Serialize(jsonData);            
    }

【讨论】:

  • 这会导致响应返回 SOAP/XML。 tempuri.org">{"Message":"Hello World"}
猜你喜欢
  • 2010-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
  • 2011-03-27
  • 1970-01-01
相关资源
最近更新 更多