WebClient为任何url下载空白字符串,但仅在Web服务器上下载

本文关键字:下载 Web 服务器 字符串 任何 url 空白 WebClient | 更新日期: 2023-09-27 18:23:59

我已经使用我的MVC Web应用程序在本地测试了下面的代码,它在本地运行良好,但在我的实时Web服务器上测试时总是返回一个空白字符串,我尝试了不同的UserAgent值,但没有成功,我还在Web服务器上安装了一个windows表单应用程序,并测试了代码,但下载良好。我想这可能是我的web.config文件中的一些设置,但我对web.config文件的工作原理知之甚少。

public class Web
    {
        private const string UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0";
        public static string DownloadPage(string url)
        {
            var client = new WebClient();
            client.Encoding = System.Text.Encoding.UTF8;
            client.Headers[HttpRequestHeader.UserAgent] = UserAgent;
            return client.DownloadString(url);
        }
    }

WebClient为任何url下载空白字符串,但仅在Web服务器上下载

您确定不需要进行身份验证吗?

您不需要UserAgent。试着这样,这就是我让它工作的方式。您现在至少可以看到它将抛出的异常。

    public string RequestUrl(string reqUrl)
    {
        WebClient client = new WebClient();
        try
        {
            return client.DownloadString(reqUrl);
        }
        catch (Exception e)
        {
            return "" + e;
        }
    }