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)

而已.

  • 我的 .net WebClient 突然开始从使用以下“用户代理”设置的 https 站点获取 403 禁止错误:“Mozilla/4.0(兼容;MSIE 6.0;Windows NT 5.2;.NET CLR 1.0.3705;)” . 用“其他”替换它解决了这个问题。有人能告诉我为什么吗? (2认同)

tom*_*dox 7

我在尝试从 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)

该解决方案来自此答案


Dev*_*onk 5

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;


phi*_*gen 1

我在 IE 中收到 403,我猜您需要登录才能检索资源。您的浏览器可能缓存了凭据,但您的应用程序并非旨在让您登录。或者您是否在浏览器中登录了 Google - 尝试注销并查看您是否仍然可以访问......