我需要一些帮助。请对我温柔一点,我还不是专家。
问题是我试图通过 JSON 将数据从客户端(浏览器)发送到服务器(网络服务)。 当我在 Fiddler 中查看 POST 数据时,我可以看到我发送的 JSON。这是有效的(已测试)。 但是我的网络服务(当我手动测试然后我得到返回 OK)时,返回以下内容:“{“消息”:“处理请求时出错。”,“StackTrace”:“”,“ExceptionType”:““}”
很遗憾,它仅供内部使用,因此我无法为您发布网络服务。
谁能给我解释一下这是怎么回事?
1.) Javascript 代码:
<script>
var markers = "{param1:1, param2:\"test\"}";
$.ajax({
type: "POST",
url: "http://xxx.xxx.xxx.xxx/site/util.asmx/CreateMarkers",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ Markers: markers }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
</script>
2.) asmx代码
<%@ WebService Language="C#" Class="site.Util" %>
using System;
using System.Web.Services;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
namespace site{
[WebService(Namespace="http://xxx.xxx.xxx.xxx/site/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Util: WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string CreateMarkers(int param1, string param2)
{
return "OK";
}
}
最佳答案
尝试格式化发送的数据以匹配网络服务方法
<script>
var markers = {param1:1, param2:"test"}; //<-- format the model
$.ajax({
type: "POST",
url: "http://xxx.xxx.xxx.xxx/site/util.asmx/CreateMarkers",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify(markers), //<-- just send the markers
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
</script>
关于c# webservice 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42022236/