简体   繁体   中英

Why does the Web API controller get null data from client through POST request?

I have an AngularJS app sending an object array to a Web API controller method through a POST request. On the server I have the following method definition:

[HttpPost]
[Route("Active")]
public async Task<IHttpActionResult> Post(IList<Media> mediaFiles)
{
    try
    {
        foreach (var file in mediaFiles)
        {
            await Task.Factory.StartNew(() => PublicData.SetInactiveMedia(file.Id, file.Active));
        }
        return Ok();
    }
    catch (ArgumentException e)
    {

        return BadRequest(e.Message);
    }
}

I use the $resource factory in order to interact with the server (but I have to mention that I have also tried with $http and no difference showed up). This is the method:

var activeMedia = $resource('/api/adminhotspotsmedia/active', { save: { method: 'POST' } });
var setActiveMedia = function (mediaFiles) {
            activeMedia.save(mediaFiles);
        }

The mediaFiles variable is an array of objects that absolutely match the Media model on the server.

In the Developer's Console I can see this Request Payload associated with the request:

在此处输入图片说明

So the array is trying to get to the server, but it cannot. The server gets a null value for the list of objects. I will add that I have tried using:

  • [FromBody] tag
  • dynamic instead of IList<Media>
  • IList<object> instead of IList<Media>

The problem persists. What could it be?

By default the model binder wont know what to do with the interface unless you have a custom model binder that knows what to expect and what the desired behavior is.

Alternatively you can use an actual List<Media>

[HttpPost]
[Route("Active")]
public async Task<IHttpActionResult> Post(List<Media> mediaFiles) { ... }

or array Media[]

[HttpPost]
[Route("Active")]
public async Task<IHttpActionResult> Post(Media[] mediaFiles) { ... }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM