当数据键没有要发送的数据时,以下代码正确执行,即数据:"{}"空JSON对象,而webservice不带参数.我想将一些数据发布到网络服务,但我遇到了麻烦.
当我尝试将其设置为数据时:"{'name':'Niall','surname':'Smith'}",我收到错误
{"Message":"Invalid web service call, missing value for parameter: \u0027json\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
Web服务未执行.
这是我的Jquery调用,将我的数据发布回服务器.
$.ajax({ type: "POST", url: "/WebServices/BasketServices.asmx/AddItemToBasket", data: "{'name':'niall'}", // Is this Correct?? contentType: "application/json; charset=utf-8", dataType: "json", success: OnItemAddedSuccess }); function OnItemAddedSuccess(result,eventArgs) { //deserialize the JSON and use it to update the Mini Basket var response = JSON.parse(result.d); }
这是我的WebService
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService] public class BasketServices : System.Web.Services.WebService { [WebMethod(true)] public string AddItemToBasket(string json) { //do stuff return myString.toJSON(); } }
问题是什么?是要发布的JSON数据的格式吗?可能是我没有在我的WebService上设置正确的属性.Dave Ward的帖子中提到的问题怎么样?
我已经尝试了我能想到的一切.有没有人有任何想法?
我认为webservice期望设置参数json
.试试这个AJAX调用:
var data = {'name':'niall'}; $.ajax({ type: "POST", url: "/WebServices/BasketServices.asmx/AddItemToBasket", data: "json=" + JSON.stringify(data), contentType: "application/json; charset=utf-8", dataType: "json", success: OnItemAddedSuccess });
哪种JSON.stringify()
方法类似于"官方"实现中的方法:http://json.org/js.html
上面的解决方案对我不起作用.所以相反,我做了以下.1.)确保javascript对象属性(此处为ID和Quantity)具有相同的名称和相同的类型(在本例中为number == int)作为webservice的参数2.)不要将对象包装到一个数据传输对象(DTO),但只是字符串化他们感谢Yasin Tarim给了我需要的提示让它工作
// javascript object var cartItem = {"ID": 123, "Quantity": 2} $.ajax({ type: "POST", url: "/WebServices/BasketServices.asmx/AddItemToBasket", data: JSON.stringify(cartItem), contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { OnSuccess(cartItem, data); }, });
// ASMX Server Side Code [WebMethod(Description = "Add item to ShoppingCart")] [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] public string AddItemToBasket(int ID, int Quantity) { CartItem cI = new CartItem(); cI.iD = ID; cI.qty = Quantity; CartItem.SaveToDatabase(ci); return "foo from Webservice - it worked"; }