c# - webclient 远程服务器返回错误 : (500) Internal Server Error

标签 c# httpwebrequest webclient

我正在尝试使用 webclient 下载网页并出现 500 内部错误

public class AsyncWebClient
    {
        public string GetContent(string url)
        {
            return GetWebContent(url).Result.ToString();
        }
        private Task<string> GetWebContent(string url)
        {
            var wc = new WebClient();
            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();

            wc.DownloadStringCompleted += (obj, args) =>
            {
                if (args.Cancelled == true)
                {
                    tcs.TrySetCanceled();
                    return;
                }

                if (!String.IsNullOrEmpty(args.Result))
                    tcs.TrySetResult(args.Result);
            };

            wc.DownloadStringAsync(new Uri(url));
            return tcs.Task;
        }
    }

并调用:

var wc =new AsyncWebClient();
var html = wc.GetContent("http://truyen.vnsharing.net/");    >> always get the above error

如果我使用其他网站,那么它工作得很好。不知道这个网站有什么特别之处。

请帮忙!!

最佳答案

服务器很可能需要一个正确的用户代理。

将您的代码更新为以下内容:

var wc = new WebClient();
wc.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();

关于c# - webclient 远程服务器返回错误 : (500) Internal Server Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14919683/

相关文章:

c# - 在 WPF 中从一个窗口切换到另一个窗口并使其处于事件状态

c# - 在 VisualStudio 中创建 IronPython 项目时出错; "Exception has been thrown by the target of an invocation."

c# - NHibernate 重新创建每个关联项

.net - 异步 Web 请求最佳实践

c# - ASHX 处理程序中的异步发布

.net - ASP.NET 中的 Web 服务器回调 Web 浏览器客户端机制

c# - 是否有自动为您格式化代码的 TFS checkin 策略?

php - 在 PHP 中发出 REST API 请求

wpf - 为什么 BitmapImage RequestCachePolicy 会被忽略?

c# - 如何通过 Windows Phone 7 将数据传递给 Asp.net Web API