Asp.Net WebApi,REST控制器和字节数组反序列化

时间:2013-08-30 12:32:55

标签: c# asp.net-mvc-4 json.net deserialization

我已经实现了这样的控制器:

[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 obream设置为null的Person obj。

为了测试我使用的ImageStream字符串是否正确,我尝试了这个:

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

1 个答案:

答案 0 :(得分:2)

在您的Javascript代码中,您没有将字节数组传递给C#方法,而是传递字符串。它们不是同一件事。如果要传递字节数组,则需要是一个实际的数字数组,其值介于0到255之间。

试试这样:

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