Webbrowser in ASP.net

2019-07-23 09:14发布

问题:

i'm trying to use WebBrowser in ASP.net but i found an error from Thread

        WebBrowser webget = new WebBrowser();
        webget.Navigate("aaaaaa");
        HtmlDocument d = webget.Document;
        Console.WriteLine(d);
        Console.Read();

The error is :

Unable to instantiate ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' because the current thread is not a single-threaded apartment (STA) thread.

回答1:

this is an expected behavior as asp.net was designed for concurrency and will not mak any since using STA and this due to message pumping

try this instead

  string documentText= null;     
     var thread =  new Thread(() =>
     {

             var webget = new WebBrowser();
             webget.Navigated += webget_Navigated;
             webget.Navigating += webget_Navigating;
             webget.DocumentCompleted +=webget_DocumentCompleted;
             webget.ScriptErrorsSuppressed = true;


             webget.Navigate("http://hooooooooo.com");
             while (documentText == null)
             {
                 documentText = webget.DocumentText;
             }
     });
     thread.SetApartmentState(ApartmentState.STA);    
        thread.Start();
        while (documentText == null)
        {
            var t = Task.Delay(TimeSpan.FromSeconds(1));
            Task.WaitAll(t);
        }

if you are using this in asp.net you should do the following

<system.web>     
    <httpRuntime apartmentThreading="true" targetFramework="4.6.2" />
  </system.web>