【问题标题】:Can't Get .Net Web Service to Return Json无法让 .Net Web 服务返回 Json
【发布时间】:2012-04-20 13:21:20
【问题描述】:

我已经阅读了这里的帖子并尽我所知,但仍然无法让我的网络服务返回 json。

网络服务,.Net 4.0

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment     the following line. 
[System.Web.Script.Services.ScriptService]
public class JsonWS : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string Sum()
{
    string x = "1", y = "2";
    return x + y;
}

}

这是我的 jquery 调用。

<script>
$(function () {
    $('#btn_test').click(function () {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "http://localhost/jsontest/JsonWS.asmx/Sum",
            dataType: "json",
            success: function (json) {
                alert(json.d);
            },
            error: function () {
                alert("Hit error fn!");
            }
        });
    });
});

此错误 b/c web 服务正在返回...

<string xmlns="http://tempuri.org/">12</string>

谢谢。

【问题讨论】:

  • GET请求是否成功?
  • 获取请求也不起作用。我读过的其他帖子提到它只适用于帖子。
  • 你试过Accept: application/json HTTP header吗?
  • 刚刚尝试添加 Accept 标头。没有帮助。
  • 加法的有趣定义...

标签: jquery .net json web-services


【解决方案1】:

说明

你得到字符串是因为你返回了一个字符串。你应该返回一个对象。 该对象将被转换为 JSON。

样本

public class MyClassName 
{
   public string x { get; set }
   public string y { get; set }
}

[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public MyClassName Sum()
{
    return new MyClassName { x = "1", y = "2" };
}

更新

您也可以返回匿名类型。在这种情况下,您不需要对象 MyClassName

[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public MyClassName Sum()
{
    return new { x = "1", y = "2" };
}

更多信息

【讨论】:

【解决方案2】:

更新:

无法让跨域 (jsonp) 与 Web 服务一起使用,因此切换到 .aspx 页面并使用 Response.Write() 将逻辑放入 Page_Load。像魅力一样工作。

对于刚开始从事此类工作的人的警告,请注意“回调=?”参数。另一个要注意的是,刷新和关闭您的响应对于除 Chrome 之外的所有浏览器都是可以的,因为这会向浏览器发送一个响应,表明该流已被服务器关闭。 Chrome 以不同的方式处理这个问题。放手就好了。

【讨论】:

    猜你喜欢
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多