C# 更改 WebBrowser 控件的用户代理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/937573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:45:23  来源:igfitidea点击:

Changing the user agent of the WebBrowser control

c#winformswebbrowser-controluser-agent

提问by Proximo

I am trying to change the UserAgent of the WebBrowser control in a Winforms application.

我正在尝试更改 Winforms 应用程序中 WebBrowser 控件的 UserAgent。

I have successfully achieved this by using the following code:

我通过使用以下代码成功实现了这一点:

[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(
    int dwOption, string pBuffer, int dwBufferLength, int dwReserved);

const int URLMON_OPTION_USERAGENT = 0x10000001;

public void ChangeUserAgent()
{
    List<string> userAgent = new List<string>();
    string ua = "Googlebot/2.1 (+http://www.google.com/bot.html)";

    UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, ua, ua.Length, 0);
}

The only problem is that this only works once. When I try to run the ChangeUserAgent() method for the second time it doesn't work. It stays set to the first changed value. This is quite annoying and I've tried everything but it just won't change more than once.

唯一的问题是这只能工作一次。当我第二次尝试运行 ChangeUserAgent() 方法时,它不起作用。它保持设置为第一个更改的值。这很烦人,我已经尝试了所有方法,但它不会改变不止一次。

Does anyone know of a different, more flexible approach?

有谁知道一种不同的、更灵活的方法?

Thanks

谢谢

采纳答案by Jean Azzopardi

I'm not sure whether I should just copy/paste from a website, but I'd rather leave the answer here, instead of a link. If anyone can clarify in comments, I'll be much obliged.

我不确定我是否应该只从网站复制/粘贴,但我宁愿将答案留在这里,而不是链接。如果有人可以在评论中澄清,我将非常感激。

Basically, you have to extend the WebBrowser class.

基本上,您必须扩展 WebBrowser 类。

public class ExtendedWebBrowser : WebBrowser
{
    bool renavigating = false;

    public string UserAgent { get; set; }

    public ExtendedWebBrowser()
    {
        DocumentCompleted += SetupBrowser;

        //this will cause SetupBrowser to run (we need a document object)
        Navigate("about:blank");
    }

    void SetupBrowser(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        DocumentCompleted -= SetupBrowser;
        SHDocVw.WebBrowser xBrowser = (SHDocVw.WebBrowser)ActiveXInstance;
        xBrowser.BeforeNavigate2 += BeforeNavigate;
        DocumentCompleted += PageLoaded;
    }

    void PageLoaded(object sender, WebBrowserDocumentCompletedEventArgs e)
    {

    }

    void BeforeNavigate(object pDisp, ref object url, ref object flags, ref object targetFrameName,
        ref object postData, ref object headers, ref bool cancel)
    {
        if (!string.IsNullOrEmpty(UserAgent))
        {
            if (!renavigating)
            {
                headers += string.Format("User-Agent: {0}\r\n", UserAgent);
                renavigating = true;
                cancel = true;
                Navigate((string)url, (string)targetFrameName, (byte[])postData, (string)headers);
            }
            else
            {
                renavigating = false;
            }
        }
    }
}

Note: To use the method above you'll need to add a COM reference to “Microsoft Internet Controls”.

注意:要使用上述方法,您需要添加对“Microsoft Internet Controls”的 COM 引用。

He mentions your approach too, and states that the WebBrowser control seems to cache this user agent string, so it will not change the user agent without restarting the process.

他也提到了你的方法,并指出 WebBrowser 控件似乎缓存了这个用户代理字符串,所以它不会在不重新启动进程的情况下更改用户代理。

回答by Constantin

The easiest way:

最简单的方法:

webBrowser.Navigate("http://localhost/run.php", null, null,
                    "User-Agent: Here Put The User Agent");

回答by natenho

Also, there is a refresh option in the function (according to MSDN). It worked well for me (you should set it before any user agent change). Then the question code could be changed like this:

此外,函数中有一个刷新选项(根据MSDN)。它对我来说效果很好(您应该在任何用户代理更改之前设置它)。那么问题代码可以这样更改:

[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(
    int dwOption, string pBuffer, int dwBufferLength, int dwReserved);

const int URLMON_OPTION_USERAGENT = 0x10000001;
const int URLMON_OPTION_USERAGENT_REFRESH = 0x10000002;

public void ChangeUserAgent()
{
    string ua = "Googlebot/2.1 (+http://www.google.com/bot.html)";

    UrlMkSetSessionOption(URLMON_OPTION_USERAGENT_REFRESH, null, 0, 0);
    UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, ua, ua.Length, 0);
}

回答by harsimranb

I'd like to add to @Jean Azzopardi's answer.

我想补充@Jean Azzopardi 的回答。

void BeforeNavigate(object pDisp, ref object url, ref object flags, ref object targetFrameName,
        ref object postData, ref object headers, ref bool cancel)
{
    // This alone is sufficient, because headers is a "Ref" parameters, and the browser seems to pick this back up.
    headers += string.Format("User-Agent: {0}\r\n", UserAgent);
}

This solution worked best for me. Using the renavigating caused other weird issues for me, like the browser content suddenly vanishing, and sometimes still getting Unsupported Browser. With this technique, all the requests in Fiddler had the correct User Agent.

这个解决方案最适合我。使用重新导航给我带来了其他奇怪的问题,比如浏览器内容突然消失,有时仍然得到不受支持的浏览器。使用这种技术,Fiddler 中的所有请求都有正确的用户代理。