Using a System.Windows.Forms.WebBrowser inside ASP web form

C

CodeRazor

I am converting a windows application which contains a web browser control
into an ASP.net application.

The Windows project references all manner of html controls in the WebBrowser
control and retrieves values using the HtmlControlCollection class etc.

I was hoping I was going to be able to work with the
Windows.Forms.WebBrowser object from inside my ASP.net webform by simply
adding a reference to System.Windows.Forms and doing code like below:

WebBrowser webBrowser = new WebBrowser();
webBrowser.DocumentText = "<html><body>my document</body></html>;
HtmlDocument htmlDocument = webBrowser.Document;

However, it blows up with the following error:
ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be
instantiated because the current thread is not in a single-threaded
apartment.

Is there any way to get round this problem. It would save having to totally
rewrite this project.

Many thank,

CodeRazor
 
S

Seraphim Prozorov

System.Windows.Forms.WebBrowser is a COM-object, so, it needs Single Thread Appartment (STA), if you need to use it in ASP.NET application, you need to create another STA thread, for example:

public class Default : Page
{
string html;
bool isThreadFinished;

protected void Page_Load(object sender, EventArgs e)
{
html = string.Empty;
isThreadFinished = false;

Thread th = new Thread(BrowserThread);
th.SetApartmentState(ApartmentState.STA);
th.Start("www.yandex.ru");

while (!isThreadFinished) { }
Response.Write(html);
}

[STAThread]
void WebBrowserExample(object url)
{
System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
wb.InitializeLifetimeService();
wb.Navigate(url.ToString());
this.html = wb.Version;
isThreadFinished = true;
}
}

But you can't use objet System.Windows.Forms.WebBrowser, as a server web-control, because it is Windows Forma control.
If you need to display another web-resource on your page, use <iframe> html tag.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top