简体   繁体   English

c#HttpWebRequest 404,对象不完整列表返回null

[英]c# HttpWebRequest 404, return null on object not entire List

I have a code that retrieves Json value from a Api link. 我有一个从Api链接检索Json值的代码。 This is deserialized and stored as object in a list. 它反序列化并作为对象存储在列表中。 The ID values in this list are then used to retrieve other Json values from a different Api link. 然后,此列表中的ID值用于从其他Api链接中检索其他Json值。 Only these Id's have a possibility to not exist in the second Api link. 只有这些ID才有可能在第二个Api链接中不存在。 If this is the case all that is shown is {"text":"no such id"} and the program crashes with a 404 error. 如果是这种情况,显示的所有内容都是{"text":"no such id"} ,程序崩溃并显示404错误。

This is the code: 这是代码:

public RootObject objFromApi_idExistListings(string url)
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            try
            {
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    var jsonReader = new JsonTextReader(reader);
                    var serializer = new JsonSerializer();
                    return serializer.Deserialize<RootObject>(jsonReader);
                }
            }
            catch (WebException)
            {
                return null;
            }
        }

When a 404 is hit it returns everything null from there on. 命中404时,它将返回所有null。 Not only that single Api request and then continues, no the entire list is then returned null. 不仅该单个Api请求然后继续,而且没有整个列表返回空值。

How do i get around to only make that object return null and everything else continues. 我该如何解决,只能使该对象返回null,其他所有操作都会继续。 Or how do i skip the entire making of that object when its a 404, doesnt have to be returned null as long as the code can continue going and deserialize all left Api links it has to work through. 或者,如果代码可以继续运行并反序列化所有必须通过的左侧Api链接,则不必跳过该对象的整个过程,而不必返回404。

You could use something like this to bail out if there is a 404 response (or any response other than 200). 如果有404响应(或200以外的任何响应),则可以使用类似的方法来纾困。

try
{
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode != System.Net.HttpStatusCode.OK) return null;
    //Continue by getting and parsing the response stream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM