c# - 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);
}
任何帮助是极大的赞赏。
解决方案
我面临着同样的问题。以下解决方案经过测试并且工作正常。
看起来您的模型或视图模型包含 IFromFile 接口。下面的例子
[NotMapped]
public IFormFile logoFile { get; set; }
- 首先从模型或视图模型中删除 IFromFile
- 对于文件上传,使用 IFromFile 作为控制器中的参数
public async Task<IActionResult> Create(MyModel model,IFormFile logoFile) { }
- 删除带有以下输入标签的默认脚手架输入剃刀标签
<form enctype="multipart/form-data">
<input name="logoFile"/>
<form/>
推荐阅读
- git - 将 git 存储库从本地拉到远程
- go - 是否可以将嵌入文件显示为文件名?
- postgresql - 如何在二进制文件中使用 deadpool-postgres crate,在库中使用 postgres crate?
- php - 阻止访问 sitemap.php 但允许 sitemap.xml
- python - Python:将字符串列转换为日期时间列('%d/%m/%YT%H:%M:%S')
- firebase - 如何在 Flutter 中为 Firebase 身份验证构建自定义电子邮件操作处理程序
- python - Python APScheduler 失败:“仅支持 pytz 库中的时区”错误
- angular - 使用 ts-morph 在声明 NgModule 中添加组件
- django - Django从模型中的分区获取数据
- visual-studio - Visual Studio 2019 安装程序一直无法下载离线安装程序包?