【问题标题】:.NET CSV Uploader Allow Nulls.NET CSV 上传器允许空值
【发布时间】:2018-06-30 08:46:29
【问题描述】:

我已经组合了一个我认为可以工作的 CSV 导入器,虽然我得到了这个错误,我如何允许这个列为空,所以当它添加到表中时它会自动设置 ID?我试过了:

csv.Configuration.WillThrowOnMissingFields = false;

但它无法识别,这是我尝试上传时遇到的错误:

CsvHelper.ValidationException: '找不到与索引 0 处的 ['ID'] 名称匹配的标头。如果您希望缺少某些标头并希望忽略此验证,请将配置 HeaderValidated 设置为 null。您还可以更改功能以执行其他操作,例如记录问题。'

    [HttpPost]
    [ActionName("CreateBulk")]
    public ActionResult CreateBulkUpload()
    {
        object db;
        var file = Request.Files["attachmentcsv"];
        using (var csv = new CsvReader(new StreamReader(file.InputStream), true))
        {
            var records = csv.GetRecords<Client>().ToList();
            foreach (var item in records)
            {
                var strip = item.homePage.Replace("https://www.", "").Replace("http://www.", "")
                    .Replace("https://", "").Replace("http://", "").Replace("www.", "");

                string[] URLtests =
                    {"https://www." + strip, "http://www." + strip, "https://" + strip, "http://" + strip};

                string[] Metric = MajesticFunctions.MajesticChecker(URLtests);
                var userId = User.Identity.GetHashCode();
                var UserTableID = 1;

                var newclient = new Client

                {
                    clientN = item.clientN,
                    homePage = Metric[0],
                    clientEmail = item.clientEmail,
                    monthlyQuota = item.monthlyQuota,
                    TrustFlow = Int32.Parse(Metric[1]),
                    CitationFlow = Int32.Parse(Metric[2]),
                    RI = Int32.Parse(Metric[3]),
                    MJTopicsID = item.MJTopicsID,
                    UserTableID = UserTableID
                };
                ViewBag.newdomain = newclient;
                return RedirectToAction("Index");
            }
        }
        return RedirectToAction("Index");

    }

【问题讨论】:

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


    【解决方案1】:

    您是否尝试过错误消息中提到的建议? 像这样?

     csv.configuration.HeaderValidated = null; 
    

    【讨论】:

    • @啊是的!抱歉,虽然我现在有一个新问题,但确实解决了这个问题,哈哈,谢谢
    • 不客气,仔细检查错误消息总是值得的,希望开发人员花一些时间编写有意义的错误消息 ;-)
    【解决方案2】:

    确保包含这两行:

    csv.Configuration.HeaderValidated = null;
    
    csv.Configuration.MissingFieldFound = null;
    

    【讨论】:

      【解决方案3】:

      The developer made some breaking changes this year,因此接受的答案将不再有效。

      相反,你必须提前创建一个配置对象并将其注入到构造函数中:

      var config = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
           HeaderValidated = null
        };
      using (var reader = new StreamReader(file))
      using (var csv = new CsvReader(reader, config))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-22
        • 1970-01-01
        • 1970-01-01
        • 2022-09-26
        • 2011-07-14
        • 2013-05-11
        • 1970-01-01
        相关资源
        最近更新 更多