views:

34

answers:

2

I have a web service, created using C#. For some reason, it seems to throw a 500 internal server error whenever I invoke my exposed method. I set some breakpoints and found the following line is what does it:

m_Browser = new WebBrowser();

Any idea why this line would cause my service to crash? The WebBrowser control is in the System.Windows.Forms namespace.

+3  A: 

That's probably because as the documentation clearly states it

The WebBrowser class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.

while a web service runs in a multi thread apartment mode (MTA). This same article shows a hack that could be used to run your web service in an STA mode but the performance of doing so might decrease.

Clearly a WebBrowser control is not meant to be used in a web service but in a client application with a GUI. So usually when you are trying to use something into a scenario that this something is not meant for, there's a price to pay.

Darin Dimitrov
A: 

The same issue is documented for the iMacros web macro recorder here:

http://wiki.imacros.net/Web_Scripting#How_to_run_iMacros_unattended

The workaround mentioned there is to run iMacros (= the application with the webbrowser control!) in the "RemoteInteractive" mode (see Windows Logon Types for more details). We use approach and it works well for our project (web scraping).

SamMeiers