我正在尝试使用IFormfile&发布文件其他属性使用swagger模拟asp.net core web api中的数据,但我可以同时做任何事情(上传文件和其他模型属性)。
请建议我这样做的好方法。
答案 0 :(得分:1)
可能如下......
[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.
}
}
}
答案 1 :(得分:1)
您可以创建一个具有字符串和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.
}
}
}