我最近在一个相当广泛的REST API上编写了概念证明,以支持我们的遗留数据组件。但是我发现它在处理更大的数据集(40k +项目)时运行得非常慢。
经过一番研究后,我在SO上发现了一个主题,声称使用memorystream
,HttpClientHandlers
更有效率,更重要的是使用Gzip
进行压缩。所以我更新了我当前的.NET版本并开始在VS2017中重写API。
(应该提到我从未使用过这些数据结构)
然后我在示例中跟随,但已撞墙。我在尝试从API中获取一些数据时收到此错误消息(这只是错误的片段):
“消息”:“发生错误。”,“ExceptionMessage”:“不能 将当前JSON对象(例如{\“name \”:\“value \”})反序列化为 类型 'System.Collections.Generic.List`1 [RESTWebApi.Models.TRK_TrackerFeatures]'
这是代码:
public async Task<IHttpActionResult> GetAll()
{
DataSet ds = dc.FETCHTRK_TrackerFeatures("", conStr, "");
List<TRK_TrackerFeatures> arr = new List<TRK_TrackerFeatures>();
foreach (DataTable table in ds.Tables)
{
foreach (DataRow row in table.Rows)
{
int? id = row["ID"] as int?;
String trackercode = row["TrackerCode"] as String;
Boolean? applicabletoproject = row["ApplicableToProject"] as Boolean?;
int? trk_feature_lkid = row["TRK_Feature_LKID"] as int?;
int? trk_trackerstatus_lkid = row["TRK_TrackerStatus_LKID"] as int?;
int? trk_trackerstatus_lkid2 = row["TRK_TrackerStatus_LKID2"] as int?;
Boolean? readyforwork = row["ReadyForWork"] as Boolean?;
String action = row["Action"] as String;
String responsibleperson = row["ResponsiblePerson"] as String;
int? tminus = row["TMinus"] as int?;
DateTime? datetobeactioned = row["DateToBeActioned"] as DateTime?;
int? trk_startdateid = row["TRK_StartDateID"] as int?;
String accountableperson = row["AccountablePerson"] as String;
String comments = row["Comments"] as String;
DateTime? datestamp = row["DateStamp"] as DateTime?;
arr.Add(new TRK_TrackerFeatures
{
ID = id,
TrackerCode = trackercode,
ApplicableToProject = applicabletoproject,
TRK_Feature_LKID = trk_feature_lkid,
TRK_TrackerStatus_LKID = trk_trackerstatus_lkid,
TRK_TrackerStatus_LKID2 = trk_trackerstatus_lkid2,
ReadyForWork = readyforwork,
Action = action,
ResponsiblePerson = responsibleperson,
TMinus = tminus,
DateToBeActioned = datetobeactioned,
TRK_StartDateID = trk_startdateid,
AccountablePerson = accountableperson,
Comments = comments,
DateStamp = datestamp
});
}
}
using (HttpClientHandler handler = new HttpClientHandler())
{
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (HttpClient client = new HttpClient(handler, false))
{
string json = JsonConvert.SerializeObject(arr);
byte[] jsonBytes = Encoding.UTF8.GetBytes(json);
MemoryStream ms = new MemoryStream();
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress, true))
{
gzip.Write(jsonBytes, 0, jsonBytes.Length);
}
ms.Position = 0;
StreamContent content = new StreamContent(ms);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
content.Headers.ContentEncoding.Add("gzip");
HttpResponseMessage response = await client.PostAsync("http://localhost:61090/api/TRK_TrackerFeatures/GetAll", content);
List<TRK_TrackerFeatures> results = await response.Content.ReadAsAsync<List<TRK_TrackerFeatures>>(); <== error here
Debug.WriteLine(String.Join(", ", results)); //
}
}
return Ok();
}