我可以在IE中手动下载.
但是,使用以下代码
WebClient client = new WebClient();
client.DownloadFile(address, filename);
Run Code Online (Sandbox Code Playgroud)
显示例外:403禁止
怎么了?我怎样才能做到这一点?
其他
Bor*_*rg8 67
只需在下载之前添加一行简单的行:
string url = ...
string fileName = ...
WebClient wb = new WebClient();
wb.Headers.Add("User-Agent: Other"); //that is the simple line!
wb.DownloadFile(url, fileName);
Run Code Online (Sandbox Code Playgroud)
而已.
我在尝试从 SharePoint 网站 url 下载图像时遇到了这个问题。在我的情况下user-agent,在标题中将设置为其他或空白是不够的,我必须user-agent如下设置:
client.Headers.Add("user-agent", " Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
Run Code Online (Sandbox Code Playgroud)
该解决方案来自此答案。
403也可能是由TLS问题引起的。要进行验证,您应该检查WebException.Response对象的文本。
catch (WebException ex)
{
if (ex.Response != null)
{
var response = ex.Response;
var dataStream = response.GetResponseStream();
var reader = new StreamReader(dataStream);
var details = reader.ReadToEnd();
}
}
Run Code Online (Sandbox Code Playgroud)
如果是TLS,请尝试将其添加到代码中以强制使用TLS1.2。
对于.net4:
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
对于.net4.5或更高版本:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
我在 IE 中收到 403,我猜您需要登录才能检索资源。您的浏览器可能缓存了凭据,但您的应用程序并非旨在让您登录。或者您是否在浏览器中登录了 Google - 尝试注销并查看您是否仍然可以访问......