Mahdi Saneipour
Mahdi Saneipour

Reputation: 64

Getting 400 Error when i want to post a file and and string with ApiController Asp.Net Core

i tried to send a post with i IFormFile and a string to my ApiController but im getting 400 error, when i send the file alone it works well but when i want to send the string im getting 400 error even when i just want to send string i get 400 error

My Javascript :

    let avatarModel = new FormData();

    avatarModel.set("file", blob);
    avatarModel.set("productId", productId.value);

    var xhr = new XMLHttpRequest();

    xhr.responseType = 'json';
    xhr.open('POST', '/Api/Admin/UploadProductImageForEdit', true);
    xhr.send(avatarModel);

    xhr.onreadystatechange = async function () {

        if (this.readyState == 4 && this.status == 200) {

        }
    }

My ApiController :

    [HttpPost]
    [Route("UploadProductImageForEdit")]
    [Produces("application/json")]
    public IActionResult UploadProductImageForEdit(IFormFile file, string productId)
    {
        //..//

        return Ok();

    }

enter image description here

--Update

i found out that it says that my productId field is is null but i don't know why, i even putted manual value for it

enter image description here enter image description here enter image description here

thanks for your time

i want to send a IFormFile and a string to my ApiController with method post and not getting 400 error

Upvotes: 0

Views: 223

Answers (1)

Mahdi Saneipour
Mahdi Saneipour

Reputation: 64

well, after some research and looking some projects i decided to add [FromFile] behind the productId and it worked, i don't know why it can recieve file without [FromFile] but can't do the same with productId but anyways,

here it is

[HttpPost]
    [Route("UploadProductImageForEdit")]
    [Produces("application/json")]
    public IActionResult UploadProductImageForEdit(IFormFile file, [FromForm] string productId)
    {
        ...
    }

Upvotes: 0

Related Questions