你好我想知道你怎么能在表格中发送POCO
和files
。我的问题是双重的:
Request.Form.Files[0]
并将其复制到一个文件中时,我得到一个0kb
文件。MyPoco
对象,当我使用[FromBody]
作为我的方法的参数时,我得到一个不支持类型的415
。形成
<form id="createForm" method="post" enctype="multipart/form-data" action="http://localhost:8300/api/create">
<input type="text" bind="@model.Name"/>//some binding here
<input type="text" bind="@model.Id"/> //some binding...
<input type="file"/>
</form>
调节器
[HttpPost]
[Route("api/create")]
public async Task<long> CreateAsync([FromBody] MyPoco poco) { //getting error 415 when using the FromBody
try {
MyPoco poc = poco;
string path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"file.csv"); //copy the input file -> getting 0kb file
FileStream stream = new FileStream(path, FileMode.Create);
await this.Request.Form.Files[0].CopyToAsync(stream);
return 3;
} catch (Exception) {
return 0;
}
}
P.S绑定的语法是blazor
,但在这种情况下它并不重要。
避免使用[FromBody]
,它将指示ModelBinder读取整个有效负载,然后将其序列化为MyPoco
的实例。
为了实现您的目标,您可以声明您的操作方法如下:
[HttpPost("[action]")]
public IActionResult Test(MyPoco myPoco,IFormFile myfile){
// now you get the myfile file and the myPoco
}
然后发送具有完整名称的字段:
<form id="createForm" method="post" enctype="multipart/form-data" action="/api/SampleData/Test">
<input name="MyPoco.Name" type="text" bind="@model.Name" />
<input name="MyPoco.Id" type="text" bind="@model.Id" />
<input name="myfile" type="file" />
<button type="submit">submit this form</button>
</form>
演示截图: