Search code examples
c#webapi

Could not post value to web API using IFormFile


I have a web application that does an action to upload image to API the code like this:

[HttpPost]
public async Task<IActionResult> Upload([FromForm] UploadModel model)
{
    var upload = AccountApi.UploadFile(model);
    return Ok("OK");
}

public static object UploadFile(UploadModel model)
{
    RestClient client = InitClient();
    request.Resource = "Account/UploadFile";
    request.Method = Method.POST;
    request.AddJsonBody(model);
    IRestResponse<object> response = client.Execute<object>(request);
    return response.Data;
}

public class UploadModel
{
    public long UserId { get; set; }
    public string Token { get; set; }
    public IFromFile File { get; set; }
}

and there's a web API to handle Rest request above the code like this:

[HttpPost("UploadFile")]
public async Task<object> UploadFileAction(UploadModel model)
{
    // the code handle upload file request here
    return "Success";
}

my issue is the UploadModel model in web application contains the right value that requested from front-end (UserId = 10, Token = "eyJ..........", File = [object]) but when it posted to API, the 3 properties in UploadModel didn't get the value posted from web application (UserId = 0, Token = null, File = null).

Could you help me to find the solution for this?


Solution

  • I found the solution myself. instead of using IFormFile to post, I serialized the image file to a base64 string and post it over API. and in API, I convert it to File object Thanks for following my question