C# 如何在WebClient中设置用户代理

C# 如何在WebClient中设置用户代理,c#,webclient,user-agent,C#,Webclient,User Agent,我使用下面的代码打开youtube视频的流请求,但它总是返回一个异常。远程服务器返回一个错误:NotFound。然后我尝试使用Fiddler来检测问题,我看到WebClient自动将用户代理字段设置为NativeHost,而不是我的用户代理,如下所示 我向youtube发送请求的代码: 请给我一些建议。非常感谢尝试添加用户代理 web.Headers.Add("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.h

我使用下面的代码打开youtube视频的流请求,但它总是返回一个异常。远程服务器返回一个错误:NotFound。然后我尝试使用Fiddler来检测问题,我看到WebClient自动将用户代理字段设置为NativeHost,而不是我的用户代理,如下所示

我向youtube发送请求的代码:


请给我一些建议。非常感谢

尝试添加用户代理

web.Headers.Add("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)")

请尝试此操作以添加用户代理

web.Headers.Add("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)")

您可以使用此代码

using (WebClient web = new WebClient())
    {
    web.Headers["User-Agent"] =
    "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
    "(compatible; MSIE 6.0; Windows NT 5.1; " +
    ".NET CLR 1.1.4322; .NET CLR 2.0.50727)";
      }

您可以使用此代码

using (WebClient web = new WebClient())
    {
    web.Headers["User-Agent"] =
    "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
    "(compatible; MSIE 6.0; Windows NT 5.1; " +
    ".NET CLR 1.1.4322; .NET CLR 2.0.50727)";
      }

你也可以这样做

using (WebClient webClient = new WebClient())
{
      webClient.Headers.Add("user-agent", "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Safari/537.36");
}

你也可以这样做

using (WebClient webClient = new WebClient())
{
      webClient.Headers.Add("user-agent", "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +http://www.google.com/bot.html) Safari/537.36");
}