为什么文件IFormFile = null?

时间:2019-02-07 09:27:28

标签: c# asp.net-core asp.net-core-webapi

[Route("api/file")]
[Produces("application/json")]
[Consumes("application/json", "application/json-patch+json", "multipart/form-data")]
[ApiController]
public class FileController : ControllerBase
{
    public FileController()
    {
    }

    [HttpPost]
    public async Task<IActionResult> PostProfilePicture([FromQuery]IFormFile file)
    {
        var stream = file.OpenReadStream();
        var name = file.FileName;
        return null;
    }
}

邮递员

enter image description here

调试

enter image description here

最后的文件= null 如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

您将其作为x-www-form-urlencoded发送。您必须将其作为multipart/form-data发送。文件只能在此模式下上载,因此IFormFile在所有其他模式下也将是null

x-www-form-urlencoded是默认模式,仅用于在请求正文中发送密钥/值编码对。

也不需要[FromQuery],因为您不能通过查询参数上传文件。

答案 1 :(得分:1)

您需要更改选择模型绑定程序将从其解析IFormFile实例的源的属性。代替[FromQuery][FromForm]

public async Task<IActionResult> PostProfilePicture([FromForm]IFormFile file)

答案 2 :(得分:1)

我猜您从IFormFile中得到的是空值,因为您在Controller类而不是controller方法上指定了此操作的必需属性。如下更新代码即可解决问题。

[Route("api/file")]
[ApiController]
public class FileController : ControllerBase
{

    public FileController()
    {

    }

    [HttpPost]
    [Produces("application/json")]
    [Consumes("multipart/form-data")]
    public async Task<IActionResult> PostProfilePicture([FromForm]IFormFile file)
    {
        var stream = file.OpenReadStream();
        var name = file.FileName;
        return null;
    }
}

希望这可以解决您的问题。