2013-08-30 163 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

相关问题