Leonardo
Leonardo

Reputation: 11401

Binding failing for form data

I have a webapi that is supposed to receive a file upload.
The general definition is:

[Route("/{rdmId}/files/{fileName}")]
public class RDMFilesController : Controller
{
    /// <summary>
    /// Creates a new file for the given RDM. If the file already exists an error is returned.
    /// </summary>
    /// <returns></returns>
    [HttpPut]
    public async Task<IActionResult> PUT(string rdmId, string fileName, [FromForm]IFormFile file)
    {
         // DO STUFF
    }
}

On the Do Stuff part, if you check, file is null. But if you check Request.Form.Files[0] the file is there!

What am I doing wrong? I was expecting that file to be populated...

Edit 1: the client side so far is a Postman following this tutorial

Upvotes: 2

Views: 729

Answers (3)

MayankGaur
MayankGaur

Reputation: 993

Can you please try this, this will surely help you.

[Route("{rdmId}/files/{fileName}")]
public class RDMFilesController : Controller
{
    /// <summary>
    /// Creates a new file for the given RDM. If the file already exists an error is returned.
    /// </summary>
    /// <returns></returns>
    [HttpPut]
    public async Task<IActionResult> PUT([BindRequired, FromRoute]string rdmId, [BindRequired, FromRoute]string fileName, [FromForm]IFormFile file)
    {
         // DO STUFF
    }
}

Upvotes: 0

mxmissile
mxmissile

Reputation: 11681

Since Request.Form.Files[0].Name == "file" is false, it will not bind. Without the names matching its not going to work. In Postman, make sure your key is set to "file".

Upvotes: 1

Hadi Samadzad
Hadi Samadzad

Reputation: 1540

You should decorate rdmId and fileName arguments with [FromRoute] attribute like this:

    [HttpPut]
    public async Task<IActionResult> PUT([FromRoute]string rdmId, [FromRoute]string fileName, [FromForm]IFormFile file)
    {
         // DO STUFF
    }

Also you should put rdmId and fileName in the route and send file as Body -> form-data in Postman with key=file.

enter image description here

Upvotes: 2

Related Questions