简体   繁体   English

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

[英]Asp.Net WebApi, REST controller and byte array deserialization

i have implemented a controller like this: 我已经实现了这样的控制器:

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

Person is this class: 人是这个阶层:

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

At client side i make this call to post new Person: 在客户端,我发出此呼叫以发布新人员:

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);
            }
});

The problem is that i receive the Person obj with ImageStream set as null. 问题是我收到ImageStream设置为null的Person obj。

To test if ImageStream string that i use is correct i tried this: 要测试我使用的ImageStream字符串是否正确,我尝试了以下操作:

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

In your Javascript code you are not passing a byte array to your C# method, you're passing a string. 在Javascript代码中,您没有将字节数组传递给C#方法,而是在传递字符串。 They are not the same thing. 它们不是同一件事。 If you want to pass a byte array, it needs to be an actual array of numbers whose values are between 0 and 255. 如果要传递字节数组,则它必须是一个实际的数字数组,其值在0到255之间。

Try it like this: 像这样尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 asp.net webapi POST 中使用序列化或反序列化期间出错 - Error during serialization or deserialization using in asp.net webapi POST 从ASP.NET中的控制器类返回byte []数组 - Return a byte[] array from controller class in ASP.NET 在ASP.NET MVC中找不到WebApi控制器 - WebApi controller not found in ASP.NET MVC ASP.net WebAPI控制器目录/路由 - ASP.net WebAPI controller directory/ routing 如何将字节数组值从AngularJS传递到Asp.net WebAPI? - How to pass byte array values from AngularJS to Asp.net WebAPI? 在asp.net WebAPI中返回数组对象 - Return array object in asp.net WebAPI 如何在asp.net核心webapi项目中如何将多个参数传递给控制器​​,其中一个参数是文件或字节[] - How in asp.net core webapi project you can pass multiple parameters to a controller where one of them is file or a byte[] 如何为ASP.NET Core中的Controller Action覆盖默认反序列化? - How to override default deserialization for Controller Action in ASP.NET Core? ASP.NET Core 中每个控制器的不同 JSON 反序列化设置 - Different JSON deserialization settings per controller in ASP.NET Core Asp.net WebApi:找不到与名为'xxxx'的控制器匹配的类型 - Asp.net WebApi : No type was found that matches the controller named 'xxxx'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM