具有文件和正文的WebAPI方法

时间:2019-01-24 08:37:40

标签: c# asp.net-core

我有一个如下所示的WebAPI方法。上载文件就可以了,但是我还需要一个附加对象,其中包含有关如何处理文件的信息。到目前为止,我已经尝试过:

//Works fine but no body defined
[HttpPut("{id}")]
public IActionResult Put(string id, IFormFile file)
{
    //Do stuff
    return StatusCode(200);
}

public class UploadFile
{
    //As simple example
    public string Description { get; set; }
    public Dictionary<string, string> Keys { get; set; }
}

//What I would like to have, but doesn't work
[HttpPut("{id}")]
public IActionResult PutTest(string id, IFormFile file, [FromBody] UploadFile info)
{
    //Do stuff
    return StatusCode(200);
}

通过以下输入使用SwaggerUI:

enter image description here

我收到一条消息"The input was not valid."的400错误请求。 SwaggerUI显示以下用于请求的cURL(似乎在主体上不包含任何信息):

curl -X PUT "https://localhost:5001/api/Document/test/test.txt" -H  "accept: application/json" -H  "Content-Type: multipart/form-data" -d {"file":{}}

我怎样才能最好地获得我想要的结果?

1 个答案:

答案 0 :(得分:1)

您是否尝试将IFormFile和UploadFile包装到单个视图模型中:

Name    |   unit_price  |   total_amount
j1      |   2           |   5000
j1      |   200         |   1000
j2      |   3           |   7500
j2      |   100         |   500
j3      |   4           |   10000
j3      |   300         |   1500

然后

public class FileViewModel{ 
    public UploadFile UploadFile{get;set;} 
    public IFormFile File {get; set;}
}