Home > Net >  C# File Upload: Web Method Not Accepting Form Data Sent Along With Uploaded File
C# File Upload: Web Method Not Accepting Form Data Sent Along With Uploaded File

Time:11-08

My web method:

    [HttpPost]
    public async Task<IActionResult> UploadFile2(IFormFile file, int idPackage)
    {
        string output = $"{file.FileName} - {file.Length} - {idPackage}";
        return Ok(output);
    }

My Postman request:

POST https://localhost:7006/api/upload/UploadFile2 HTTP/1.1
User-Agent: PostmanRuntime/7.29.2
Accept: */*
Postman-Token: fc51918c-f03f-4e29-9726-6a5159dcb035
Host: localhost:7006
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------368567246425722572627984
Content-Length: 363

----------------------------368567246425722572627984
Content-Disposition: form-data; name="idPackage"

1247
----------------------------368567246425722572627984
Content-Disposition: form-data; name="file"; filename="dummy.dat"
Content-Type: application/octet-stream

dummy data from the dummy file
----------------------------368567246425722572627984--

The file parameter correctly receives the uploaded file as input.

The idPackage parameter remains the default value of 0, even though I am sending along 1247 for this value.

What could possibly be causing this?

Update 1

This very same web request does work in another project of mine, I just found out.

It has to be some sort of server side setting, related to how requests are handled, although I currently have no idea which one.

Update 2

I figured it had to be the Newtonsoft JSON resolver configuration that I have in my other project.

Turns out that wasn't it. Still no idea what it could be, then.

Is there any way of debugging how C# processes a web request under the hood?

CodePudding user response:

Maybe I'm going to say something stupid, but try to create a DTO class

DTO:

public class UploadFileDTO 
{
     public IFormFile File { get; set; } 
     public int IdPackage { get; set; }
}

Method

    [HttpPost]
    public async Task<IActionResult> UploadFile2([FromForm] UploadFileDTO input)
    {
        string output = $"{input.File.FileName} - {input.File.Length} - {input.IdPackage}";
        return Ok(output);
    }

Source: How to upload an IFormFile with additional parameters

CodePudding user response:

I just solved this by adding the [FromForm] attribute in front of the extra parameter.

[HttpPost]
public async Task<IActionResult> UploadFile2(IFormFile file, [FromForm]int idPackage)
{
    string output = $"{file.FileName} - {file.Length} - {idPackage}";
    return Ok(output);
}

Why this didn't need to be done in my older production project, but not my newer sandbox project... I do not know.

I'm guessing they changed something with newer .NET versions and/or Nuget packages.

I found the solution by coming across this guy's code snippet.

  • Related