skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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; }    
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search