Home > other >  ASP.Net API how to let API accept an IFromFile and an object at the same API call
ASP.Net API how to let API accept an IFromFile and an object at the same API call

Time:01-03

I have the following API that works properly

[HttpPost("testing")]
public string Testing(IFormFile file, string str, int num)
{
  return str   num.ToString();
}

What I want to do ideally is to pass "str" and "num" in an object instead of each param on its own

Like this:

public class Testdto
{
  public int Num{ get; set; }
  public string Str { get; set; }
}

[HttpPost("testing")]
public string Testing(IFormFile file, testdto dto)
{
 return dto.str   dto.num.ToString();
}

Of course the above format rends an error, it does not work.

Is there a way to make it work? My real API body is quite large and contains nested objects so I can't just pass them all as params in the API

CodePudding user response:

add the FromForm Attribute :

[HttpPost("testing")]
        public string Testing(IFormFile file, [FromForm]testdto dto)
        {
            return dto.str   dto.num.ToString();
        }

And add the parameters to request form

The result:

enter image description here

CodePudding user response:

You can also create class having properties as IFormFile and other fileds.

And pass it to your controller with [FromForm] attribute

Sample Code:

 [HttpPost]
 [Route("FileUpload")]
 public ActionResult FileUploaded([FromForm] PostRequest postRequest) {

          return Ok(postRequest.str);
 }

 public class PostRequest {
     public int num { get; set; }           
     public string str { get; set; }           
     public IFormFile file { get; set; }    
 }
  • Related