【问题标题】:WebClient.DownloadString throws a 'System.Net.WebException'WebClient.DownloadString 抛出“System.Net.WebException”
【发布时间】:2019-10-21 03:40:42
【问题描述】:

WebClient.DownloadString 每次运行都会失败,在 System.dll 中引发“System.Net.WebException”。它的调用方式有问题吗?代码如下。

using (var wc = new WebClient())
            {
                wc.Headers["Authorization"] = string.Format("Basic {0}", ConfigurationManager.AppSettings["which_api_token"]);
                try
                {
                    var jsonString = wc.DownloadString(string.Format("{0}/subjects/{1}", 
                            ConfigurationManager.AppSettings["which_api_url"], 
                            Uri.EscapeDataString(subjectName)));
                    return result;
                }
                catch(Exception ex)
                {
                    result.Status = ResultStatus.Failed;
                    return result;
                }
           }

【问题讨论】:

  • 异常的信息是什么?可能会有所启发
  • 你没有对 Exception 做任何事情你正在“捕捉”... 将这行代码插入你的 catch 块 throw new Exception(ex.Message); 并摆脱 return result; 这将让您更好地理解错误(这次请不要忘记与我们分享错误)

标签: c# html .net webclient


【解决方案1】:

WebException 给你错误。

using (var wc = new WebClient())
{
    wc.Headers["Authorization"] = string.Format("Basic {0}", ConfigurationManager.AppSettings["which_api_token"]);
    try
    {
        var jsonString = wc.DownloadString(string.Format("{0}/subjects/{1}", 
                ConfigurationManager.AppSettings["which_api_url"], 
                Uri.EscapeDataString(subjectName)));
        return result;
    }
    catch(Exception ex)
    {
        WebException we = ex as WebException;
        if (we != null && we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            // it can be 404, 500 etc...
            Console.WriteLine(response.StatusCode);
        }
        result.Status = ResultStatus.Failed;
        return result;
    }
}

【讨论】:

    猜你喜欢
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多