问题
I'm trying to send a image and textfields to a api endpont but i'm reciving "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.
回答1:
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; }
回答2:
Maybe you should try with application/x-www-form-urlencoded instead of multipart/form-data
回答3:
Here is a working example for what you are looking for
Controller:
[HttpPost]
public async Task<IActionResult> SaveFile([FromForm] IFormFile file) {
// Your code here
}
And inside your model:
public IFormFile File { get; set; }
Change async Task<IActionResult> if you don't need it...
来源:https://stackoverflow.com/questions/54411250/how-to-send-multipart-form-data-to-asp-net-core-web-api