IFormFile always return null in asp.net core 2.1

2020-03-21 02:25发布

Api method is looks like below

    [HttpPost]
    public async Task<BaseListResponse<MediaStorageModel>> MediaBrand(IFormFile file, int brandId)
    {
        var files = new List<IFormFile>();
        files.Add(file);

        var response = await this.Upload(files, "brand", brandId);

        return response;
    }

My postman configuration enter image description here

Upgrade my dotnet core from 2.0 to 2.1 thie become not working, can anyone help about this. What going wrong

10条回答
欢心
2楼-- · 2020-03-21 02:39

The below code should work

[HttpPost]
public async Task<BaseListResponse<MediaStorageModel>> MediaBrand([FromQuery] int brandId, IFormFile file)
{
    var files = new List<IFormFile>();
    files.Add(file);

    var response = await this.Upload(files, "brand", brandId);

    return response;
}
查看更多
虎瘦雄心在
3楼-- · 2020-03-21 02:41

Update [FromForm] attribute, and don't put parameter into Headers, and put name of key is file and brandId.

I tested, It is Ok Add [FromForm] attribute

Only form-data and key is correct

查看更多
相关推荐>>
4楼-- · 2020-03-21 02:43

Make sure the form is the correct enctype

<form asp-action="Edit" enctype="multipart/form-data">

I also had to change how the Model bind from the generated

public async Task<IActionResult> Edit([Bind("Text,Example")] Example example)

to

public async Task<IActionResult> Edit(Example example)
查看更多
Emotional °昔
5楼-- · 2020-03-21 02:48

Change your method argument to take below model and add [FromForm], it should work.

public class FileUploadViewModel
{
    public IFormFile File { get; set; }
    public int BrandId { get; set; }
}

public async Task<BaseListResponse<MediaStorageModel>> MediaBrand([FromForm] FileUploadViewModel viewModel)
查看更多
爷、活的狠高调
6楼-- · 2020-03-21 02:49

In your form use

enctype="multipart/form-data"

查看更多
Evening l夕情丶
7楼-- · 2020-03-21 02:55

I have found a workaround to make it work:

Use HttpPut instead of HttPost on the controller action.

I was also surprised by this behavior. If someone can explain why it fixes the issue, it would help me.

查看更多
登录 后发表回答