如何将multipart/form-data发送到asp.net核心Web API? [英] How to send multipart/form-data to asp.net core web api?

查看:821
本文介绍了如何将multipart/form-data发送到asp.net核心Web API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像和文本字段发送到api endpont,但是我正在接收不支持的内容类型'multipart/form-data; boundary = -------------- ------------ 81801171514357 这是一个ASP.NET Core 2.1 Web api.

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.

我有这个:

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

我的模特:

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

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

然后我使用axios:

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?

我尝试添加:

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

但没有成功.

然后我尝试:

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

该方法可以运行,但是信息对象上的属性为空:(

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

更新: 解决方案,不要使用JsonProperty PropertyName.使用变量名.

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

推荐答案

也许您应该尝试使用[FromForm]属性装饰控制器输入和模型? 在此处查看更多信息:

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)

在模型中:

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

[FromForm(Name="name")]
public string Name { get; set; }

这篇关于如何将multipart/form-data发送到asp.net核心Web API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆