首页 > 解决方案 > CSV 帮助程序异常 MissingMethodException:未找到构造函数“Microsoft.AspNetCore.Http.IFormFile()”

问题描述

将 CsvHelper 多个版本更新到最新版本 21.1.0 后,我在尝试读取通过表单提交的 CSV 文件时收到以下异常:

An unhandled exception occurred while processing the request.
MissingMethodException: Constructor 'Microsoft.AspNetCore.Http.IFormFile()' was not found.
CsvHelper.ObjectCreator.GetConstructorNotFoundException(Type type, Type[] argTypes)

ReaderException: An unexpected error occurred.
IReader state:
ColumnCount: 0
CurrentIndex: 9
HeaderRecord:
[""]
IParser state:
ByteCount: 0
CharCount: 877
Row: 2
RawRow: 2
Count: 55
RawRecord:
12345,12345,jon,,doe,doe,,,,,test@example.com,Female,4/21/2014,example,example,FALSE,FALSE,FALSE,jane,doe,9999999999,test@example.com,,111,S,Main,,St,City,CA,90210,,,,,,,,,,,,,,,,,,,,,,,,

当前索引 9 是我想要接受空白字符串并将其转换为空值的列。在模型中,其设置为字符串类型。有多个这样的列,更新后似乎都有问题。这些是可选字段。

这是控制器的简化版本:

[HttpPost]
public async Task<IActionResult> FileImport(FileViewModel fileViewModel)
{
IFormFile file = fileViewModel.File;
var fileExt = Path.GetExtension(file.FileName);

using (var stream = file.OpenReadStream())
{
    using (var reader = new StreamReader(stream))
    {
        var csvConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            MissingFieldFound = null,
            TrimOptions = TrimOptions.Trim,
            ShouldSkipRecord = record => record.All(string.IsNullOrEmpty)
        };

        var csvReader = new CsvReader(reader, csvConfiguration);

        csvReader.Context.RegisterClassMap<CustomMapProfile>();

        var test = csvReader.GetRecords<RowViewModel>().ToList(); //FAILS HERE WHILE DEBUGGING
    }
}
        
}

地图配置文件示例

    public CustomMapProfile()
    {
        AutoMap(CultureInfo.InvariantCulture);
    }

任何帮助是极大的赞赏。

标签: c#.netasp.net-corecsvhelper

解决方案


我面临着同样的问题。以下解决方案经过测试并且工作正常。

看起来您的模型或视图模型包含 IFromFile 接口。下面的例子

[NotMapped]
public IFormFile logoFile { get; set; }
  1. 首先从模型或视图模型中删除 IFromFile
  2. 对于文件上传,使用 IFromFile 作为控制器中的参数

public async Task<IActionResult> Create(MyModel model,IFormFile logoFile) { }

  1. 删除带有以下输入标签的默认脚手架输入剃刀标签

<form enctype="multipart/form-data">
<input name="logoFile"/>
<form/>


推荐阅读