1

I have recently upgraded from .NET 6 to .NET 8 where one of the existing API which accepts IFormFile and string data got impacted like the string data is coming as empty. As far as I know in .NET 8 the [FromForm] attribute is not needed so I removed that from the Angular UI and passing it as formdata. Not sure why still the data is coming as empty but file is passed. Can anyone help how to resolve this?

My API sample

From UI I will be passing as form

public async Task<ActionResult> upload(IFormFIle file, string data)
{
    // ....
}
upload(file: File, data: string): Observable<any> {
  const formData: FormData = new FormData();
  formData.append('file', file, file.name);
  formData.append('data', data);

  return this.http.post(this.apiUrl, formData);
}

2 Answers 2

0

This is basically a dupe of asp.net core web API file upload and "form-data" multiple parameter passing to method .

You can not use multiple form parameters in the controller action (for e.g. form and body params). You need to encapsulate your parameters into one param object, as described in the linked post.

Sign up to request clarification or add additional context in comments.

Comments

0

I know in .NET 8 the [FromForm] attribute is not needed so I removed that from the Angular UI and passing it as formdata. Not sure why still the data is coming as empty but file is passed. Can anyone help how to resolve this?

When the [ApiController] attribute applies an inference rule for action parameters of type IFormFile and IFormFileCollection. The multipart/form-data request content type is inferred for these types, so there is no need to add the [FromForm] attribute. But for the string type parameters it is no easier to inferred. So, we have to add the FromForm attribute before it. Since the parameter might be empty, you can modify your code as below:

public async Task<ActionResult> upload(IFormFile file, [FromForm]string? data)
{
    // ....
}

or

public async Task<ActionResult> upload([FromForm]IFormFile file, [FromForm]string? data)
{
    // ....
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.