Asp.net web api 如何在asp.net core webapi中上载包含其他模型属性的文件?
我正在尝试使用asp.net core web api中的IFormfile和其他属性模型数据发布文件,但我找到了同时完成这两项工作(上载文件和其他模型属性)的方法Asp.net web api 如何在asp.net core webapi中上载包含其他模型属性的文件?,asp.net-web-api,asp.net-core,swagger,asp.net-core-webapi,Asp.net Web Api,Asp.net Core,Swagger,Asp.net Core Webapi,我正在尝试使用asp.net core web api中的IFormfile和其他属性模型数据发布文件,但我找到了同时完成这两项工作(上载文件和其他模型属性)的方法 请给我建议一些好方法 它可以如下所示 [HttpPost("/upload/{var1}")] public async Task Upload(string var1, IFormFile file) { if (file == null) throw new Exception("File is null");
请给我建议一些好方法 它可以如下所示
[HttpPost("/upload/{var1}")]
public async Task Upload(string var1, IFormFile file)
{
if (file == null) throw new Exception("File is null");
if (file.Length == 0) throw new Exception("File is empty");
using (Stream stream = file.OpenReadStream())
{
using (var binaryReader = new BinaryReader(stream))
{
// Save the file here.
}
}
}
您可以创建具有string和IFormFile属性的模型,并使用[FromForm]属性:
public class UploadModel{
public string Var1 { get; set; }
public IFormFile File { get; set; }
}
在控制器中:
[HttpPost("/upload")]
public async Task Upload([FromForm] UploadModel model)
{
if (model.File == null) throw new Exception("File is null");
if (model.File.Length == 0) throw new Exception("File is empty");
model.Var1 += "hello world";
using (Stream stream = file.OpenReadStream())
{
using (var binaryReader = new BinaryReader(stream))
{
// Save the file here.
}
}
}
请用一些代码更新您的问题,以及您迄今为止所做的选择/努力。注意,您也可以将端点参数设置为
ifformfile myFile、[FromForm]specific objecttype otherData