【发布时间】:2018-01-30 21:45:44
【问题描述】:
我一直在搜索和阅读并尝试了许多不同的变体,以确保讨厌的 {"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(),但没有成功。这只会返回 JSON,但也会返回一个错误,指出在发送标头后无法刷新。我使用了 Write.End() 而不是 CompleteRequest,这也会从 JSON 响应中截断 ]。我将返回一个字符串,而不是使用 Context.Response.Write,但是,这也会在 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);
}
});
非常感谢任何想法/建议!
【问题讨论】:
标签: c# asp.net json web-services asmx