【问题标题】:CSV Helper Exception MissingMethodException: Constructor 'Microsoft.AspNetCore.Http.IFormFile()' was not foundCSV 帮助程序异常 MissingMethodException:未找到构造函数“Microsoft.AspNetCore.Http.IFormFile()”
【发布时间】:2021-01-23 00:50:12
【问题描述】:

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

非常感谢任何帮助。

【问题讨论】:

  • 您需要显示CustomMapProfileRowViewModel。我假设您在 RowViewModel 中有一个 IFormFile 作为属性,这显然不起作用,因为您无法实例化接口。

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


【解决方案1】:

我遇到了同样的问题。以下解决方案已经过测试并且运行良好。

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

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

public async Task&lt;IActionResult&gt; Create(MyModel model,IFormFile logoFile) { }

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

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

【讨论】:

    猜你喜欢
    • 2010-09-17
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多