【问题标题】:Posting complex objects with form?用表单发布复杂的对象?
【发布时间】:2020-05-05 11:00:50
【问题描述】:

我在 REACT 中有以下内容:

let form = new FormData();
form.append("test",test);

for (var index = 0; index < files.length; index++) {
  var element = files[index];
  form.append('file', element);
}

axios.post('https://localhost:44371/api/default', form,'sdfdsf')
        .then((result) => {
            console.log(result);
        })
        .catch((ex) => {
            console.error(ex);
        });

这在 asp.net core web api 中:

[HttpPost]
public void Post(IFormCollection form,string test2)
{
    var test = form["test"];

    foreach (var file in form.Files)
    {
        UploadFile(file);
    }
}

它按预期工作。我可以将键作为字符串添加到表单中并在 API 中提取它们。但是无论如何要通过表单传递复杂类型吗?如果我将对象作为参数附加到 API 函数上,则最佳选择。或者它是一个限制,当发布一个你可以发布的表单时?​​p>

【问题讨论】:

  • 普通形式的帖子基于application/x-www-form-urlencoded,所以它只是一个键值对列表。虽然可以使用标准 ASP.NET Core 模型绑定器以这种方式具有某种层次结构,但您应该发布一个序列化的主体,例如改用 JSON。

标签: reactjs asp.net-core-webapi


【解决方案1】:

是否有通过表单传递复杂类型的方法?如果我在 API 函数上附加一个对象作为参数,则最佳选择。

要达到上述要求,可以参考下面的示例代码sn-p。

在客户端

let form = new FormData();
form.append("test", "testc");

for (var index = 0; index < files.length; index++) {
    var element = files[index];
    form.append('file', element);
}

form.append("childP.name", "blablahere");

axios.post('https://xxxxx/api/default', form, 'sdfdsf')
    .then((result) => {
        console.log(result);
    })
    .catch((ex) => {
        console.error(ex);
    });

API 控制器操作

[HttpPost]
public void Post([FromForm]TestModel testModel)
{

    var test = testModel.test;

    foreach (var file in testModel.file)
    {
        UploadFile(file);
    }

    var childp_name = testModel.childP.name;

    //code logic here
    //...
}

模型类

public class TestModel
{
    public string test { get; set; }
    public List<IFormFile> file { get; set; }
    public ChildP childP { get; set; }
}

public class ChildP
{
    public string name { get; set; }
}

测试结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    相关资源
    最近更新 更多