ASP.NET WebApi not receiving post data

2019-03-31 10:50发布

I need to receive some string and binary data using WebApi. I have created a controller this way:

    [HttpPost]
    public void Post(byte[] buffer)
    {
        // Some code goes here
    }

Here's the routtings:

    routes.MapHttpRoute(
        name: "CuscarD95B",
        routeTemplate: "D95B/{controller}",
        defaults: new { buffer = RouteParameter.Optional },
        constraints: new { controller = @"Cuscar" }

Now when I try to post some data, buffer is always byte[0] (zero length array). No data is being passed to the controller.

Any help would be appreciated.

Thanks.

6条回答
beautiful°
2楼-- · 2019-03-31 11:44

Did you try to use the HttpPostedFileBase without [FromBody] ?

public void Post(HttpPostedFileBase buffer)
查看更多
Explosion°爆炸
3楼-- · 2019-03-31 11:45

I am not sure how to send byte[] to webApi, but what you can do is to pass the binary data as Base64 string to your controller and then convert the base64 string to the byte[].

查看更多
不美不萌又怎样
4楼-- · 2019-03-31 11:50

I found the solution here. Looks like we need to create custom MediaTypeFormatter to achieve primitive type deserialization.

查看更多
何必那么认真
5楼-- · 2019-03-31 11:52

I was able to post a byte[] in my request body, and the value was successfully model bound. Was the content-type set? Note that simple string is considered to be valid JSON here, and so it should work if your request's content-type is set to application/json...

Having said that, you can simply have your POST method that expects a string from the body instead of a byte[] and set the content-type to be application/json:

[HttpPost]
public void Post([FromBody]string buffer)
{
    // Some code goes here
}
查看更多
神经病院院长
6楼-- · 2019-03-31 11:53

If you are ever struggling with deserializing a body, try and do it manually to see if you are actually sending it correctly.

[HttpPost]
public void Post()
{
    string body = Request.Content.ReadAsStringAsync().Result;
}
查看更多
不美不萌又怎样
7楼-- · 2019-03-31 11:53

We passed Json object by HttpPost method, and parse it in dynamic object. it works fine. this is sample code:

ajaxPost:
...
Content-Type: application/json,
data: {"name": "Jack", "age": "12"}
...

webapi:

[HttpPost]
public string DoJson2(dynamic data)
{
    string name = data.name;
    int age = data.age;

    return name;
}

If there is complext object type, you need to parse the dynamic type by using:

JsonConvert.DeserializeObject< YourObjectType >(data.ToString());

A complex data content sample is here, it includes array and dictionary object. {"AppName":"SamplePrice","AppInstanceID":"100","ProcessGUID":"072af8c3-482a-4b1c‌​-890b-685ce2fcc75d","UserID":"20","UserName":"Jack","NextActivityPerformers":{"39‌​c71004-d822-4c15-9ff2-94ca1068d745":[{"UserID":10,"UserName":"Smith"}]}}

查看更多
登录 后发表回答