{"d": null} 在来自 ASMX Web 服务的 JSON 响应后显示

{"d": null} showing after JSON response from ASMX Web Service

我一直在搜索和阅读并尝试了许多不同的变体,以确保讨厌的 {"d": null} 没有附加到我的 JSON 回复的末尾,但是,我不知所措。我有一个使用 Context.Response.Write 方法的 .asmx Web 服务,如下所示:

DataTable products = my_source;

string jsonResponse = JsonConvert.SerializeObject(products);//, Formatting.None, new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore} );

this.Context.Response.Clear();
this.Context.Response.ContentType = "application/json; charset=utf-8";

this.Context.Response.Write(jsonResponse);
HttpContext.Current.ApplicationInstance.CompleteRequest();

我也试过在写入后使用 Flush() 但没有成功。那只会 return 和 JSON 但也会出现一个错误,说在 headers 发送后无法刷新。我使用 Write.End() 而不是 CompleteRequest,这也会截断 JSON 响应中的 ]。而不是使用 Context.Response.Write,我会 return 一个字符串,但是,这也会在 JSON 响应末尾离开 ] 括号。

我的方法属性如下:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]

我通过简单的 ajax 请求调用服务:

$.ajax({
    url : '/ProductCatalog/ProductMasterWS.asmx/GetProducts',
    type : 'GET',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (data) {
        populate(data);
    },
    error: function(xhr, ajaxOptions, thrownError) {
        console.log(xhr.status + " " + thrownError.stack);
    }
});

非常感谢ideas/advice!

不要那样实现您的 Web 服务,只需 return 一个包含您对 Web 方法的响应的 POCO 对象。 ASMX 会为您处理剩下的事情。

在服务器端试试这个解决方案:

[WebMethod]
public void Select()
{
    String result = String.Empty;
    List<UserRole> userRoles = new UserRoleController().Select(new UserRole());
    JavaScriptSerializer js = new JavaScriptSerializer();
    result = js.Serialize(userRoles);

    Context.Response.Clear();
    Context.Response.ContentType = "application/json; charset=utf-8";
    Context.Response.Write(result);
}

我知道这是一个非常古老的问题,但我在使用 IIS 时遇到了同样的问题(在 Visual Studio 中调试不会在响应中添加“"d":null”)。

就我而言,我通过修改应用程序池解决了这个问题。默认情况下,新站点会创建一个使用 .NET CLR v4.0.30319 的新应用程序池(我使用的是 IIS v10.0.18362.1)

.NET CLR 的版本应为 v2.0.50727(集成模式)

试试这个:

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.AddHeader("content-length", res.Length.ToString());
HttpContext.Current.Response.Write(YOUR_JSON_RESPONSE);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();