Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net web api 如何在asp.net core webapi中上载包含其他模型属性的文件?_Asp.net Web Api_Asp.net Core_Swagger_Asp.net Core Webapi - Fatal编程技术网

Asp.net web api 如何在asp.net core webapi中上载包含其他模型属性的文件?

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");

我正在尝试使用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");
    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