Webbrowser in ASP.net

烂漫一生 提交于 2020-01-15 10:34:23

问题


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>


来源:https://stackoverflow.com/questions/43674732/webbrowser-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!