2013-08-30 162 views
1

我實現了一個控制器,像這樣:Asp.Net的WebAPI,REST控制器和字節數組反序列化

[HttpPost] 
[ActionName("DefaultAction")] 
public HttpResponseMessage Post(Person obj){ 
} 

人是這個類:

public class Person 
{ 
    public String Name { get; set; } 
    public byte[] ImageStream { get; set; } 
} 

在客戶端我撥打這個電話後新人:

var person={ 
      "Name":"Test", 
      "ImageStream":"AQID" 
} 

$.ajax({ 
      type: "POST", 
      url: "/person", 
      dataType: "json", 
      contentType: "application/json", 
      data: JSON.stringify(person), 
      success: function (result) { 
       console.log(result); //log to the console to see whether it worked 
      }, 
      error: function (error) { 
       alert("There was an error posting the data to the server: " + error.responseText); 
      } 
}); 

問題是,我收到Image obj的Person obj設置爲null。

爲了測試,我使用的ImageStream字符串是正確的我想這:

Person p=new Person(); 
p.Name="Test"; 
p.ImageStream=new byte[]{1,2,3}; 
String json=JsonConvert.SerializeObject(p); 

回答

2

在JavaScript代碼中你是不是傳遞一個字節數組到C#方法,你傳遞一個字符串。它們不是同一件事。如果你想傳遞一個字節數組,它需要它們的值是0到255之間,並

嘗試像這樣數字的實際數組:

var person = { 
    "Name": "Test", 
    "ImageStream": [65,81,73,68] 
} 
+0

嗨,沒有它不工作。它有時只是有效的,我的解決方案也是有效的,我不明白爲什麼。 – mantok

相關問題