【问题标题】:Can't remove .d encapsulation from JSON response in .net无法从 .net 中的 JSON 响应中删除 .d 封装
【发布时间】:2014-08-12 08:04:20
【问题描述】:

即使在伟大的博文 Never worry about ASP.NET AJAX’s .d again 之后,我也无法在我的 JSON 响应中逃脱 .d 封装。我不知道我是否做错了什么,所以我将复制我的服务器端和客户端代码。

我正在使用 Newtonsoft.JSON 库对 JSON 进行序列化。

客户端:

<script type="text/javascript">
$(function () {
    $("#bt").click(function () {
        $.ajax({
            type: "POST",
            url: "<%= Page.ResolveUrl("~/MapView.aspx/GetLocations")%>",
            data: "{ type: '<%= Page.RouteData.Values["type"].ToString() %>', id: '<%= Page.RouteData.Values["id"].ToString() %>' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            dataFilter: function(data) {
                var msg;

                if (typeof (JSON) !== 'undefined' && 
                    typeof (JSON.parse) === 'function')
                    msg = JSON.parse(data);
                else
                    msg = eval('(' + data + ')');

                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            success: function (msg) {
                console.log(msg);
            },
        });
    });
});
</script>

服务器端

    [System.Web.Services.WebMethod]
    public static string GetLocations(int id, string type)
    {
        string data = "";


        if (type == "attraction")
        {
            var attractions = db.Attraction
                                .Where(a => a.AttractionId == id)
                                .Select(p => new { p.AttractionId, p.Name, p.Description, p.Location })
                                .ToList();


            JObject attractionsJSON = new JObject(
                new JProperty("Attractions", new JArray(
                    from a in attractions
                    select new JObject(
                        new JProperty("id", a.AttractionId),
                        new JProperty("name", a.Name),
                        new JProperty("location", a.Location),
                        new JProperty("description", a.Description)
                        ))));

            data = attractionsJSON.ToString();
        }
        else if (type == "category")
        {
            var attractions = db.Attraction

                .Select(p => new { p.AttractionId, p.Name, p.Description, p.Location, p.CategoryId })
                .ToList();

            if (id != 0)
            {
                attractions = attractions.Where(a => a.CategoryId == id)
                    .ToList();
            }


            JObject attractionsJSON = new JObject(
                new JProperty("Attractions", new JArray(
                    from a in attractions
                    select new JObject(
                        new JProperty("id", a.AttractionId),
                        new JProperty("name", a.Name),
                        new JProperty("location", a.Location),
                        new JProperty("description", a.Description)
                        ))));

            data = attractionsJSON.ToString();

        }
        return data;
    }

服务器端 - 更新 1

    [System.Web.Services.WebMethod]
    public static void GetLocations(int id, string type)
    {
        string data = "";


        if (type == "attraction")
        {
            var attractions = db.Attraction
                                .Where(a => a.AttractionId == id)
                                .Select(p => new { p.AttractionId, p.Name, p.Description, p.Location })
                                .ToList();


            JArray attractionsJSON = new JArray(
                    from a in attractions
                    select new JObject(
                        new JProperty("id", a.AttractionId),
                        new JProperty("name", a.Name),
                        new JProperty("location", a.Location),
                        new JProperty("description", a.Description)
                        ));

            data = attractionsJSON.ToString();
        }
        else if (type == "category")
        {
            var attractions = db.Attraction

                .Select(p => new { p.AttractionId, p.Name, p.Description, p.Location, p.CategoryId })
                .ToList();

            if (id != 0)
            {
                attractions = attractions.Where(a => a.CategoryId == id)
                    .ToList();
            }


            JArray attractionsJSON = new JArray(
                    from a in attractions
                    select new JObject(
                        new JProperty("id", a.AttractionId),
                        new JProperty("name", a.Name),
                        new JProperty("location", a.Location),
                        new JProperty("description", a.Description)
                        ));

            data = attractionsJSON.ToString();

        }


        var js = new System.Web.Script.Serialization.JavaScriptSerializer();

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
        HttpContext.Current.Response.Write(js.Serialize(data));
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }
}

【问题讨论】:

  • 尝试从 ajax 调用中删除 dataType 参数。从same blog,看到“dataType:不关你的事”
  • @DanielJ.G.不幸的是,即使没有它,我仍然收到 .d
  • 为什么我在点击这篇文章的第一个链接时会收到“此站点包含恶意软件”警告?
  • @Mike 这一定与一些被谷歌识别为危险的恶意脚本有关。希望网站的所有者能够解决这些问题。

标签: c# jquery asp.net ajax json


【解决方案1】:

尝试使用无返回的 void 方法。而是编写输出以自己响应!

  [System.Web.Services.WebMethod]
    public static void GetLocations(int id, string type)
    {
     // var attractions = something ;

     var js = new System.Web.Script.Serialization.JavaScriptSerializer();

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
        HttpContext.Current.Response.Write(  js.Serialize(attractions )  );
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
   }

结束这两个电话非常重要:

flush : 确保将输出写入流

End : 结束流,防止 asp.Net 将空 Json 写入流

【讨论】:

  • 我认为这就是答案,而且我们似乎走上了一条好的道路,但这并不能解决我的问题。实际上,我得到的是无效的 JSON。 JSON输出可以在这里看到pastebin.com/NTWDfxtA
  • 如何使用 System.Web.Script.Serialization.JavaScriptSerializer 创建 json?
  • 是的,我以您的确切示例为例,它按预期删除了 .d,但 JSON 无效。
  • 只需将景点传递给 Serialize(),我认为不需要 Jobject、jArray
  • 每当您访问克罗地亚时,请告诉我,我欠您一杯啤酒! :) 谢谢,将景点直接传递给对象是解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2017-04-24
  • 1970-01-01
相关资源
最近更新 更多