使用www-form-urlencoded发送时,为什么我的JSON字符串在服务器端为null?
我有一个使用jquery / ajax的ASP.NET / MVC4应用程序。
我正在尝试使用$.ajax( ... )
从客户端向服务器发送一个非常大的字符串
首先,我们使用contentType "application/json"
来完美地工作。 但是,在这种特殊情况下,服务器会抛出exception,因为传输的数据太长。 我已经尝试了一切,以增加web.config文件中的反序列化器的maxJsonLength
,但它不起作用,没有人能弄明白为什么。
作为一种解决方法,有人建议将contentType作为"application/x-www-form-urlencoded; charset=UTF-8"
,然后让我的控制器手动反序列化对象而不是让MVC框架执行它。
使用Javascript:
function AjaxRequest(data, dataType, type, url, contentType, success, error, args) { if (url.indexOf("MyController/SomeMethodInMyController") > 0) contentType = "application/x-www-form-urlencoded; charset=UTF-8"; data = JSON.stringify(data); $.ajax({async: args.async, cache: args.cache, data: data, dataType: dataType, type: type, url: url, contentType: contentType, traditional: true, headers : { ... }, beforeSend: { ... }, success: { ... }, error: { ... }, complete: { ...}); } function SomeFunction() { var object = {}; object.Name = $("#someControl").val(); object.RtfData = $("someOtherControl").val(); AjaxRequest(object, 'html', 'post', 'MyController/SomeMethodInMyController', 'application/json;', function (response) { ... }, function (error) { ... }); }
在这种情况下,我的应用程序不再“整体”崩溃,MVC框架试图自己反序列化对象。 现在它绕过所有这些并直接调用我的控制器中的方法。 有点hacky,但3天后我会拿走我能得到的东西。
C#:
public void SomeMethodInMyController(string formData) { JavaScriptSerializer jss = new JavaScriptSerializer(); jss.MaxJsonLenght = int.MaxValue; MyType objMyType = jss.Deserialize(formData); //do stuff with objMyType }
问题是当我在此方法中设置断点时, formData
为null
。
在我的浏览器控制台中, $.ajax();
之前$.ajax();
实际执行我输入typeof(data)
到控制台返回"string"
。 如果我将鼠标hover在符号上,我可以看到我希望它包含的所有数据。 那么为什么我的C#代码中的值为null
?
我认为你需要发送一个FormData对象 ,而不仅仅是一个字符串。 尝试更改您的AjaxRequest
函数,如下所示:
function AjaxRequest(data, dataType, type, url, contentType, success, error, args) { if (url.indexOf("MyController/SomeMethodInMyController") > 0) contentType = "application/x-www-form-urlencoded; charset=UTF-8"; var form = new FormData(); form.append("MyData", JSON.stringify(data)); $.ajax({processData: false, async: args.async, cache: args.cache, data: form, dataType: dataType, type: type, url: url, contentType: contentType, traditional: true, headers : { ... }, beforeSend: { ... }, success: { ... }, error: { ... }, complete: { ...}); }