我面临一个奇怪的问题,在某些情况下会发生,但在常规情况下不会。我有一个 ajax 调用,它将一些数据发送到我的控制器。在大多数情况下,ajax 调用正确地将数据发布到控制器,但它失败的情况(异常)我得到一个日志,表明接收到的 json 不完整。我真的不知道这种错误行为的根本原因是什么。任何指针都会有很大帮助...
这是我的代码 -
C#
public class MyController : System.Web.Mvc.Controller {
....
....
public JsonResult doPost(string x, string y, int z) {
private JavaScriptSerializer _serialiser = new JavaScriptSerializer();
List<Dictionary<string, object>> items = _serialiser.Deserialize<List<Dictionary<string, object>>>(x);
// deserialsation throws argument exception
...
// do stuff after that...
}
...
}
异常详情
类型 - System.ArgumentException
message - 传入的未终止字符串。
堆栈跟踪 -
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeString()
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
at System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext)
at System.Web.Mvc.ValueProviderFactoryCollection.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext)
at System.Web.Mvc.ControllerBase.get_ValueProvider()
at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
Javascript
// A - is a big object
var jsonData = { x: JSON.stringify(A),
y: new Date().toString(),
z: A.Index
};
$.ajax ({
url : '/my/doPost',
type: 'POST', contentType: 'application/json; charset=utf-8;',
cache: false,
data: JSON.stringify(jsonData),
dataType: 'json',
async: true,
success: function () {
// do something on success
},
error: function (jqXhr, textStatus, errorThrown) {
// do something on error
}
});
谢谢萨尔塔克