Visual Studio сообщает, что не все код кода возвращает значение, даже если они делают

StackOverflow https://stackoverflow.com/questions/2946970

Вопрос

У меня есть API в NetMF C #, которые я пишу, который включает в себя функцию для отправки HTTP-запроса. Для тех, кто знаком с NetMF, это сильно модифицированная версия «WebClient» пример, который простая приложение, которое демонстрирует, как подать HTTP-запрос и пережить ответ. В образце он просто печатает ответ и возвращает пустоту. Однако в моей версии мне нужно, чтобы вернуть ответ HTTP.

По какой-то причине Visual Studio сообщает, что не все пути кода возвращает значение, даже если я могу сказать, они делают.

Вот мой код ...

  /// <summary>
  /// This is a modified webClient
  /// </summary>
  /// <param name="url"></param>
  private string httpRequest(string url)
  {
   // Create an HTTP Web request.
   HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;

   // Set request.KeepAlive to use a persistent connection. 
   request.KeepAlive = true;

   // Get a response from the server.
    WebResponse resp = request.GetResponse();

   // Get the network response stream to read the page data.
   if (resp != null)
   {
    Stream respStream = resp.GetResponseStream();
    string page = "";
    byte[] byteData = new byte[4096];
    char[] charData = new char[4096];
    int bytesRead = 0;
    Decoder UTF8decoder = System.Text.Encoding.UTF8.GetDecoder();
    int totalBytes = 0;

    // allow 5 seconds for reading the stream
    respStream.ReadTimeout = 5000;

    // If we know the content length, read exactly that amount of 
    // data; otherwise, read until there is nothing left to read.
    if (resp.ContentLength != -1)
    {
     for (int dataRem = (int)resp.ContentLength; dataRem > 0; )
     {
      Thread.Sleep(500);
      bytesRead = respStream.Read(byteData, 0, byteData.Length);

      if (bytesRead == 0)
       throw new Exception("Data laes than expected");

      dataRem -= bytesRead;

      // Convert from bytes to chars, and add to the page 
      // string.
      int byteUsed, charUsed;
      bool completed = false;
      totalBytes += bytesRead;
      UTF8decoder.Convert(byteData, 0, bytesRead, charData, 0,
       bytesRead, true, out byteUsed, out charUsed,
       out completed);
      page = page + new String(charData, 0, charUsed);
     }

     page = new String(System.Text.Encoding.UTF8.GetChars(byteData));
    }
    else
     throw new Exception("No content-Length reported");

    // Close the response stream.  For Keep-Alive streams, the 
    // stream will remain open and will be pushed into the unused 
    // stream list.
    resp.Close();
    return page;
   }
  }

Есть идеи? Спасибо...

Это было полезно?

Решение

Очевидно, что если (resp == null) Тогда вам все еще нужно что-то вернуть ...

Другие советы

Если то resp != null Тест не удается, метод заканчивается без возврата ничего. Вам нужно либо вернуть что-то здесь, либо бросить исключение, что поток ответа был нулевым.

На мой взгляд, это будет много Яснее, чтобы увидеть, отступаете ли вы немного более 1 пространства.

Насколько я могу сказать, если ROSC == NULL На странице ничего не возвращается

У вас нет return на случай, когда resp == null.

После page = new String(System.Text.Encoding.UTF8.GetChars(byteData));

Page = новая строка (System.text.encoding.utf8.getchars (bytedata));

---HERE ---

    }
    else
     throw new Exception("No content-Length rep
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top