如何在C#中的API响应上在错误goto下实现?

我有ID的列表,我正在遍历这些ID中的每一个以获取详细信息。在少数情况下,API调用失败。因此,我想跳过失败的API调用,并希望继续进行下一个ID API调用;类似于on error goto next。


foreach (var item in ID)

{

    try

    {

        List<string> resultList = new List<string>();

        url = string.Format(HttpContext.Current.Session["url"].ToString() + 

              ConfigurationManager.AppSettings["propertyURL"].ToString(),

              HttpContext.Current.Session["ObjectID"].ToString(), item);

        var request1 = WebRequest.Create(url);

        request1.Headers["X-Authentication"] = HttpContext.Current.Session["vaultToken"].ToString();

        request1.Method = "GET";

        request.Headers.Add("Cache-Control", "no-cache");


        //// Get the response.

        var response1 = request1.GetResponse();

        var deserializer1 = new DataContractJsonSerializer(typeof(PropertyValue[]));

        var result1 = (PropertyValue[])deserializer1.ReadObject(response1.GetResponseStream());

    }

    catch (Exception ex)

    {

    }

}

有什么可能的解决方案,即使API调用失败,foreach循环也将用于下一个ID API调用。


蓝山帝景
浏览 144回答 2
2回答

aluckdog

实际上,这更加清楚。Dictionary<int, string> resultList = new Dictionary<int, string>();foreach (var item in ID){&nbsp; &nbsp;resultList.Add(item,string.Empty);&nbsp; &nbsp;try&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Your Call Here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Add Result to resultList here&nbsp; &nbsp; &nbsp; &nbsp;var apiCallResult = apiCall(item);&nbsp; &nbsp; &nbsp; &nbsp;resultList[item] = apiCallResult;&nbsp; &nbsp;}&nbsp; &nbsp;catch&nbsp; &nbsp;{&nbsp; &nbsp;}}您可以在字典中查询ID没有结果的。
打开App,查看更多内容
随时随地看视频慕课网APP