Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send multipart/form-data to ASP.NET Core Web API?

I'm trying to send a image and text fields to an API endpoint but I'm received

Unsupported content type 'multipart/form-data; boundary=---------------------------81801171514357

This is a ASP.NET Core 2.1 Web API. I have this:

[HttpPost("/api/account"), Authorize]
public void SaveUser(UserModel info)

And my model:

    [JsonProperty(PropertyName = "avatar")]
    [DataType(DataType.Upload)]
    public IFormFile Avatar { get; set; }

    [JsonProperty(PropertyName = "name")]
    [DataType(DataType.Text)]
    public string Name { get; set; }

Then I use axios:

    var formData = new FormData();
    formData.append("avatar", imageFile);
    formData.append("name", name);
    axios.post("/api/account", formData);

I expected this method to run, not throw an exception. But how? I have tried to add:

[Consumes("application/json", "multipart/form-data")]

But no success.

Then I tried:

[HttpPost("/api/account"), Authorize]
public void SaveUser([FromForm]UserModel info)

The method runs, but the properties is empty on info object :(

UPDATE: Solution, don't use JsonProperty PropertyName. Use the variable name.

like image 680
mrcode Avatar asked Jan 28 '19 22:01

mrcode


People also ask

How do I upload files to net core web API?

In dotnet core controller you can use IFormFile Interface to get files, [HttpPost("upload-file")] public async Task<IActionResult> UploadFile([FromQuery] IFormFile file){ if(file.

How do you send a file using multipart form data?

Follow this rules when creating a multipart form: Specify enctype="multipart/form-data" attribute on a form tag. Add a name attribute to a single input type="file" tag. DO NOT add a name attribute to any other input, select or textarea tags.


1 Answers

Maybe you should try decorate controller input and model with [FromForm] attribute? See more info here: web api parameters binding.

In given example your controller action should look like this:

[HttpPost("/api/account"), Authorize]
public void SaveUser([FromForm]UserModel info)

In model:

[FromForm(Name="avatar")]
public IFormFile Avatar { get; set; }

[FromForm(Name="name")]
public string Name { get; set; }
like image 106
joostas Avatar answered Sep 30 '22 23:09

joostas