2009-07-18 83 views
2

我使用完全ajax化(使用jquery lib)和調用另一個asp.net回調頁獲取/發佈數據到服務器的asp.net頁面。 序列化JSON對象時遇到下面的錯誤我的一些網頁的用戶序列化json對象,同時調用ajax asp.net回調頁面

有一個錯誤反序列化類型...對象類型的 對象...包含無效 UTF8字節

$.ajax({ 
    type: "POST", 
    async: false, 
    url: 'AjaxCallbacks.aspx?Action=' + actionCode, 
    data: { 
     objectToSerialize: JSON.stringify(obj, null, 2) 
    }, 
    dataType: "json", 
    success: function(operationResult) { 
     //handle success 
    }, 
    error: function(xhttp, textStatus, errorThrown) { 
     //handle error 
    } 
}); 

處理這個我已經添加「contentType」選項...

$.ajax({ 
    type: "POST", 
    async: false, 
    url: 'AjaxCallbacks.aspx?Action=' + actionCode, 
    data: { 
     objectToSerialize: JSON.stringify(obj, null, 2) 
    }, 
    contentType: 'application/json; charset=utf-8', //<-- added to deal with deserializing error 
    dataType: "json", 
    success: function(operationResult) { 
     //handle success 
    }, 
    error: function(xhttp, textStatus, errorThrown) { 
     //handle error 
    } 
}); 

但現在我不能讀取這個對象在服務器端,因爲我coul d之前:

string objectJson = Request.Params["objectToSerialize"].ToString(); 

我得到以下錯誤:「對象引用未設置爲對象的實例」。

任何想法?

+0

可以檢查什麼是post參數傳遞給服務器?也許用Firebug來檢查。 – xandy 2009-07-18 14:43:25

回答

2

您在第二種情況下得到NullReferenceException的原因是因爲您在發送請求時使用application/json作爲Content-Type標頭,並且在服務器端ASP.NET期望數據在填充請求時以表單形式發送對象,因此它不包含objectToSerialize參數。您可以代替以下嘗試:

contentType: 'application/x-www-form-urlencoded; charset=utf-8' 

或用application/json堅持和人工讀取和解析請求流:

using (var reader = new StreamReader(Request.InputStream)) 
{ 
    var input = reader.ReadToEnd(); 
    var objectToSerialize = input.Split('=')[1]; 
} 
0

這是我如何解決我的問題: 既然我改變的contentType服務器認爲數據應該來自表單集合,而不是來自request.inputstream,所以我寫了函數來讀取&解碼輸入流,其餘代碼沒有變化:

/// <summary> 
    /// reads request input stream and decodes it so it can be deserialized to .net object 
    /// </summary> 
    /// <returns>decoded request input stream</returns> 
    private string GetInputStream() 
    { 
    string inputContent; 
    using (var sr = new System.IO.StreamReader(Request.InputStream)) 
     inputContent = sr.ReadToEnd(); 

    return Server.UrlDecode(inputContent); 
    } 
/// <summary> 
    /// reads request input stream and decodes it so it can be deserialized to .net object 
    /// </summary> 
    /// <returns>decoded request input stream</returns> 
    private string GetInputStream() 
    { 
    string inputContent; 
    using (var sr = new System.IO.StreamReader(Request.InputStream)) 
     inputContent = sr.ReadToEnd(); 

    return Server.UrlDecode(inputContent); 
    } 

到目前爲止這個工作。

剛剛意識到有一個類似於我的答案(2分),但沒有解碼沒有序列化.net對象將無法正常工作。 此外,我也希望剝離GetInputStream()給出的字符串從「jsonObjectName =」成功與序列化爲.net對象,類似於分裂流字符串