简体   繁体   English

IFormFile 在 asp.net core 2.1 中总是返回 null

[英]IFormFile always return null in asp.net core 2.1

Api method is looks like below Api方法如下所示

    [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我的邮递员配置在此处输入图片说明

Upgrade my dotnet core from 2.0 to 2.1 thie become not working, can anyone help about this.将我的 dotnet 核心从 2.0 升级到 2.1 后无法正常工作,任何人都可以对此提供帮助。 What going wrong出了什么问题

I've faced the same issue, I was able to fix it by applying the 'Name' named parameter to FromForm attribute with name of the File field in the form.我遇到了同样的问题,我能够通过将 'Name' 命名参数应用于表单中文件字段名称的 FromForm 属性来修复它。 It specifies which field in the form to bind to the method parameter.它指定表单中的哪个字段绑定到方法参数。 Change your method signature as shown here.更改您的方法签名,如下所示。

[HttpPost("status")]
public async Task<BaseListResponse<MediaStorageModel>> MediaBrand([FromForm(Name ="file")] IFormFile file, int brandId)

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 works from the generated code:我还必须根据生成的代码更改模型绑定的工作方式:

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

to this code:到这个代码:

public async Task<IActionResult> Edit(Example example)

In your form use在您的表单中使用

enctype="multipart/form-data" enctype="multipart/form-data"

Adding (Name = "body") to the from form worked for me添加 (Name = "body") 到 from 表单对我有用

Server Call :服务器调用

[HttpPost]
  [Route("UploadImage")]

public IActionResult UploadImage([FromForm(Name = "body")]IFormFile formData)

Client code :客户端代码

let formData = new FormData();
formData.append('body', event.target.files[0]);

const config = {
  headers: {
  'content-type': 'multipart/form-data',
  },
}

axios.post(ApiURL,formData, config);

I have found a workaround to make it work:我找到了一个解决方法来使它工作:

Use HttpPut instead of HttPost on the controller action.在控制器操作上使用HttpPut而不是HttPost

I was also surprised by this behavior.我也对这种行为感到惊讶。 If someone can explain why it fixes the issue, it would help me.如果有人可以解释为什么它可以解决问题,那将对我有所帮助。

Change your method argument to take below model and add [FromForm], it should work.更改您的方法参数以采用以下模型并添加 [FromForm],它应该可以工作。

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

public async Task<BaseListResponse<MediaStorageModel>> MediaBrand([FromForm] FileUploadViewModel viewModel)

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;
}

Update [FromForm] attribute, and don't put parameter into Headers, and put name of key is file and brandId.更新[FromForm]属性,不要把参数放到Headers里,key的名字是file和brandId。

I tested, It is Ok我测试过,没问题添加 [FromForm] 属性

只有表单数据和密钥是正确的

If you use javascript and FormData object you need set the name of each file to 'files'如果您使用 javascript 和 FormData 对象,则需要将每个文件的名称设置为“文件”

this.files.forEach((f) => {
         formData.append("files", f, `${this.path}/${f.name}`);
      }); 

if you use other name in your post you need to set it in the attribute of the post method如果您在帖子中使用其他名称,则需要在 post 方法的属性中设置它

formData.append("someName", f, `${this.path}/${f.name}`);

 public async Task<IActionResult> Post([FromForm(Name ="someName")] List<IFormFile> files)

Dont forget to set content-type不要忘记设置内容类型

'Content-Type': 'multipart/form-data'

In my case, i had an angular 6 app using a custom HttpInterceptor which adds content-type of "application/json" to every Http request along with a token before sending to an api.就我而言,我有一个使用自定义 HttpInterceptor 的 angular 6 应用程序,它在发送到 api 之前将“application/json”的内容类型与令牌一起添加到每个 Http 请求中。 Something like below.像下面这样的东西。 Remove the line with 'Content-Type': application/json .删除带有 'Content-Type': application/json Without that none of the solution here works.没有它,这里的任何解决方案都不起作用。 .Net Core is smarter now to translate whatever object u are sending to the api so far it matches the model u create for the object in angular. .Net Core 现在更智能,可以转换您发送到 api 的任何对象,到目前为止它与您为该对象创建的模型相匹配。

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class JwtHttpInterceptor implements HttpInterceptor {
  constructor() {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = localStorage.getItem('token');
      let clone: HttpRequest<any>;
      if (token) {
        clone = request.clone({
          setHeaders: {
            Accept: `application/json`,
            'Content-Type': `application/json`,
            Authorization: `Bearer ${token}`
          }
        });

In my case it works as follows in net core在我的情况下,它在网络核心中的工作方式如下

Controller:控制器:

[HttpPost]
public IActionResult ReadFormFile([FromForm]IFormFile miCsv)
{


}

Request body: Use as key the same name as the parameter请求正文:使用与参数同名的

在此处输入图片说明

Request Header: Use as Content-Type: multipart/form-data;请求头:用作内容类型: multipart/form-data; boundary=xxxxxxxxxxx the boundary can be any value边界=xxxxxxxxxxx边界可以是任何值

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 IFormFile 在 ASP.NET Core 3.0 MVC 中始终为 NULL - IFormFile is always NULL in ASP.NET Core 3.0 MVC IFormFile 始终为空(带有 MVC/Razor 的 ASP.NET Core) - IFormFile always null (ASP.NET Core with MVC/Razor) 在ASP.Net Core 2.1 MVC中,TempData始终为空 - TempData is always Null at ASP.Net Core 2.1 MVC asp.net核心2.1 ConfigurationBuilder GetSection函数返回null - asp.net core 2.1 ConfigurationBuilder GetSection function return null ASP.NET Core MVC:上传的文件很大时,IFormFile 返回 Null - ASP.NET Core MVC: IFormFile return Null when uploaded file is large IFormFile 在 ASP.NET Core 3.0 中返回 NULL - IFormFile is returning NULL in ASP.NET Core 3.0 ASP.NET Core Web Application using .NET 5.0: IFormFile always null when passing from view to controller - ASP.NET Core Web Application using .NET 5.0: IFormFile always null when passing from view to controller ASP.NET Core 2.0-配置[“ TestSecret”]始终返回null - ASP.NET Core 2.0 - Configuration[“TestSecret”] always return null ViewContext.RouteData.Values[&quot;Controller&quot;] 始终为 Null - Asp.Net Core 2.1 - ViewContext.RouteData.Values["Controller"] always Null - Asp.Net Core 2.1 使用HttpClient Alwyes Null ASP.net Core2.2将IFormFile发送到API - Send IFormFile To API using HttpClient Alwyes Null ASP.net Core2.2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM