我一直在搜索和阅读并尝试了许多不同的变体,以确保在我的JSON响应的末尾没有附加讨厌的{“d”:null},但是,我很茫然。我有一个.asmx Web服务,它使用Context.Response.Write方法,如下所示:
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);
}
});
非常感谢任何想法/建议!
答案 0 :(得分:0)
不要像这样实现您的Web服务,只需从Web方法返回包含您的响应的POCO对象。 ASMX为您完成剩下的工作。
答案 1 :(得分:0)
我知道这是一个非常老的问题,但是我使用IIS存在同样的问题(在Visual Studio中进行调试不会在响应中添加“ d”:null)。
就我而言,我解决了修改应用程序池的问题。默认情况下,新站点创建一个使用.NET CLR v4.0.30319的新应用程序池(我正在使用IIS v10.0.18362.1)
.NET CLR的版本应为v2.0.50727(集成模式)
答案 2 :(得分:-1)
尝试将此解决方案提供给服务器端:
[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);
}