CsvHelper对象引用未设置为对象实例(GetRecords问题)

时间:2018-12-31 01:26:23

标签: c# asp.net-mvc csvhelper

我正在关注this example。据我所知,当我向GetRecords端点发出请求时,GetHist调用失败,但是我不明白为什么。

我检查了

  1. 我的数据遵循c#类的确切命名约定(我从csv复制名称以在c#中创建变量名称)
  2. 文件输入路径正确。
  3. 我正在使用最新版本的CsvHelper(12.1.0)

GetData调用中的堆栈跟踪:

  

”在CsvHelper.CsvReader.GetRecordsT + MoveNext()\ r \ n在System.Collections.Generic.LargeArrayBuilder 1.AddRange(IEnumerable 1项)\ r \ n在System.Collections.Generic.EnumerableHelpers.ToArray [T ](IEnumerable 1 source)\r\n at System.Linq.Enumerable.ToArray[TSource](IEnumerable 1源)\ r \ n位于System.Linq.SystemCore_EnumerableDebugView`1.get_Items()“

我的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CsvHelper;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

public class DataController : Controller
{

    private readonly IHostingEnvironment _hostingEnvironment;

    public DataController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    [HttpGet("[action]")]
    public IEnumerable<OHLCData> GetHist()
    {
        var v=OHLCData.GetData(_hostingEnvironment);
        return v;
    }

    public class OHLCData
    {
        string time;
        double oask, hask, lask, cask, obid, hbid, lbid, cbid;
        int volume;

        //@TODO: shouldnt pass it to this class from controller, should set in startup and read in this method
        public static IEnumerable<OHLCData> GetData(IHostingEnvironment _hostingEnvironment)
        {
            string filepath = Path.Combine(_hostingEnvironment.WebRootPath, "EUR_USD.csv");
            using (var reader = new StreamReader(filepath))
            using (var csv = new CsvReader(reader))
            {
                return csv.GetRecords<OHLCData>();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在另一个SO post中找到了答案。我需要声明属性而不是字段来使对象映射起作用。即将string time;和其他更改为public string time {get;set;}