0

我知道这很笨拙,但是在我现有的 Web API 客户端代码中,我停止读取记录的方式是当我对 webRequest.GetResponse() 的调用在读取时崩溃并且找不到,并且吃到异常(我正在阅读“块/chunk”,由于调用 Web API REST 方法的手持设备的带宽限制)。

由于我的良心(可以这么说)一直困扰着我这样做(但它有效!),我想也许我可以首先获得记录的数量并利用这些知识来排除阅读超出世界的苍白/边缘,从而避免异常。

但是,从这里可以看出:为什么我的 Web API 路由被重新路由/错误路由?,我发现尝试访问多个 GET 方法没有成功 - 我只能通过消除另一个方法来调用所需的 GET 方法!

我现有的客户代码是:

private void buttonGetInvItemsInBlocks_Click(object sender, EventArgs e)
{
    string formatargready_uri = "http://localhost:28642/api/inventoryItems/{0}/{1}";
    // Cannot start with String.Empty or a blank string (" ") assigned to lastIDFetched; they both fail for some reason - Controller method is not even called. Seems like a bug in Web API to me...
    string lastIDFetched = "0"; 
    const int RECORDS_TO_FETCH = 100; 
    bool moreRecordsExist = true;

    try
    {
        while (moreRecordsExist) 
        {
            formatargready_uri = string.Format("http://localhost:28642/api/InventoryItems/{0}/{1}", lastIDFetched, RECORDS_TO_FETCH);
            var webRequest = (HttpWebRequest)WebRequest.Create(formatargready_uri); 
            webRequest.Method = "GET";
            var webResponse = (HttpWebResponse)webRequest.GetResponse(); // <-- this throws an exception when there is no longer any data left

            // It will hit this when it's done; when there are no records left, webResponse's content is "[]" and thus a length of 2
            if ((webResponse.StatusCode != HttpStatusCode.OK) || (webResponse.ContentLength < 3)) {
                moreRecordsExist = false;
            }
            else // ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 2))
            {
                var reader = new StreamReader(webResponse.GetResponseStream());
                string s = reader.ReadToEnd();
                var arr = JsonConvert.DeserializeObject<JArray>(s);

                foreach (JObject obj in arr)
                {
                    string id = (string)obj["Id"];
                    lastIDFetched = id;
                    int packSize = (Int16)obj["PackSize"];
                    string description = (string)obj["Description"];
                    int dept = (Int16)obj["DeptSubdeptNumber"];
                    int subdept = (Int16)obj["InvSubdepartment"];
                    string vendorId = (string)obj["InventoryName"];
                    string vendorItem = (string)obj["VendorItemId"];
                    double avgCost = (Double)obj["Cost"];
                    double unitList = (Double)obj["ListPrice"];

                    inventoryItems.Add(new WebAPIClientUtils.InventoryItem
                    {
                        Id = id,
                        InventoryName = vendorId,
                        UPC_PLU = vendorId,
                        VendorItemId = vendorItem,
                        PackSize = packSize,
                        Description = description,
                        Quantity = 0.0,
                        Cost = avgCost,
                        Margin = (unitList - avgCost),
                        ListPrice = unitList,
                        DeptSubdeptNumber = dept,
                        InvSubdepartment = subdept
                    });
                    // Wrap around on reaching 100 with the progress bar; it's thus sort of a hybrid determinate/indeterminate value that is shown
                    if (progressBar1.Value >= 100)
                    {
                        progressBar1.Value = 0;
                    }
                    progressBar1.Value += 1;
                }
            } // if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
        } // while

        if (inventoryItems.Count > 0)
        {
            dataGridViewGETResults.DataSource = inventoryItems;
        }
        MessageBox.Show(string.Format("{0} results found", inventoryItems.Count));
    }
    catch (Exception ex)
    {
        // After all records are read, this exception is thrown, so commented out the message; thus, this is really *expected*, and is not an "exception"
        //MessageBox.Show(ex.Message);
    }
}

}

...和 ​​Web API REST 控制器代码是:

public class InventoryItemsController : ApiController
{
    static readonly IInventoryItemRepository inventoryItemsRepository = new InventoryItemRepository();

    public IEnumerable<InventoryItem> GetBatchOfInventoryItemsByStartingID(string ID, int CountToFetch)
    {
        return inventoryItemsRepository.Get(ID, CountToFetch); 
    }

}

...和(im?)相关的存储库代码是:

public IEnumerable<InventoryItem> Get(string ID, int CountToFetch)
{
    return inventoryItems.Where(i => 0 < String.Compare(i.Id, ID)).Take(CountToFetch);
}

有人会认为我可以有这样的方法:

public IEnumerable<InventoryItem> Get()
{
    return inventoryItems.Count();
}

...由于没有参数与另一个参数不同,这将被识别(即使没有路由盛宴,昨天我所有的绥靖尝试都以可耻的方式失败了)。

4

1 回答 1

0

我发现我可以使用以下代码获得记录计数:

客户

private int getInvItemsCount()
{
    int recCount = 0;
    const string uri = "http://localhost:28642/api/InventoryItems";
    var webRequest = (HttpWebRequest)WebRequest.Create(uri);
    webRequest.Method = "GET";
    using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
    {
        if (webResponse.StatusCode == HttpStatusCode.OK)
        {
            var reader = new StreamReader(webResponse.GetResponseStream());
            string s = reader.ReadToEnd();
            Int32.TryParse(s, out recCount);
        }
    }
    return recCount;
}

private void GetInvItemsInBlocks()
{
    Cursor.Current = Cursors.WaitCursor;
    try
    {
        string lastIDFetched = "0";
        const int RECORDS_TO_FETCH = 100;
        int recordsToFetch = getInvItemsCount();
        bool moreRecordsExist = recordsToFetch > 0;
        int totalRecordsFetched = 0;

        while (moreRecordsExist)
        {
            string formatargready_uri = string.Format("http://localhost:28642/api/InventoryItems/{0}/{1}", lastIDFetched, RECORDS_TO_FETCH);
            var webRequest = (HttpWebRequest)WebRequest.Create(formatargready_uri);
            webRequest.Method = "GET";
            using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
            {
                if (webResponse.StatusCode == HttpStatusCode.OK)
                {
                    var reader = new StreamReader(webResponse.GetResponseStream());
                    string s = reader.ReadToEnd();
                    var arr = JsonConvert.DeserializeObject<JArray>(s);

                    foreach (JObject obj in arr)
                    {
                        var id = (string)obj["Id"];
                        lastIDFetched = id;
                        int packSize = (Int16)obj["PackSize"];
                        var description = (string)obj["Description"];
                        int dept = (Int16)obj["DeptSubdeptNumber"];
                        int subdept = (Int16)obj["InvSubdepartment"];
                        var vendorId = (string)obj["InventoryName"];
                        var vendorItem = (string)obj["VendorItemId"];
                        var avgCost = (Double)obj["Cost"];
                        var unitList = (Double)obj["ListPrice"];

                        inventoryItems.Add(new WebAPIClientUtils.InventoryItem
                        {
                            Id = id,
                            InventoryName = vendorId,
                            UPC_PLU = vendorId,
                            VendorItemId = vendorItem,
                            PackSize = packSize,
                            Description = description,
                            Quantity = 0.0,
                            Cost = avgCost,
                            Margin = (unitList - avgCost),
                            ListPrice = unitList,
                            DeptSubdeptNumber = dept,
                            InvSubdepartment = subdept
                        });
                        if (progressBar1.Value >= 100)
                        {
                            progressBar1.Value = 0;
                        }
                        progressBar1.Value += 1;
                    } // foreach
                } // if (webResponse.StatusCode == HttpStatusCode.OK)
            } // using HttpWebResponse
            int recordsFetched = WebAPIClientUtils.WriteRecordsToMockDatabase(inventoryItems, hs);
            label1.Text += string.Format("{0} records added to mock database at {1}; ", recordsFetched, DateTime.Now.ToLongTimeString());
            totalRecordsFetched += recordsFetched;
            moreRecordsExist = (recordsToFetch > (totalRecordsFetched+1));
        } // while
        if (inventoryItems.Count > 0)
        {
            dataGridViewGETResults.DataSource = inventoryItems;
        }
    }
    finally
    {
        Cursor.Current = Cursors.Default;
    }
}

服务器

存储库接口:

interface IInventoryItemRepository
{
    . . .
    int Get();
    . . .
}

存储库接口实现:

public class InventoryItemRepository : IInventoryItemRepository
{
    private readonly List<InventoryItem> inventoryItems = new List<InventoryItem>();
    . . .
    public int Get()
    {
        return inventoryItems.Count;
    }
    . . .
}

控制器:

static readonly IInventoryItemRepository inventoryItemsRepository = new InventoryItemRepository();

public int GetCountOfInventoryItems()
{
    return inventoryItemsRepository.Get();
}
于 2013-11-15T21:59:48.390 回答