这将完美地工作
我们需要添加带有线程的网络浏览器,否则我们将无法实例化 ActiveX 控件“8856f961-340a-11d0-a96b-00c04fd705a2”,因为当前线程不在单线程单元中。错误
这是我们可以让 webbrowser 在 asp.net 网页中工作的方式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Windows.Forms;
/// <summary>
/// Summary description for CustomBrowser
/// </summary>
public class CustomBrowser
{
public CustomBrowser()
{
//
// TODO: Add constructor logic here
//
}
protected string _url;
string html = "";
public string GetWebpage(string url)
{
_url = url;
// WebBrowser is an ActiveX control that must be run in a
// single-threaded apartment so create a thread to create the
// control and generate the thumbnail
Thread thread = new Thread(new ThreadStart(GetWebPageWorker));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
string s = html;
return s;
}
protected void GetWebPageWorker()
{
using (WebBrowser browser = new WebBrowser())
{
// browser.ClientSize = new Size(_width, _height);
browser.ScrollBarsEnabled = false;
browser.ScriptErrorsSuppressed = true;
browser.Navigate(_url);
// Wait for control to load page
while (browser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
html = browser.DocumentText;
}
}
}
在网页中
CustomBrowser browser = new CustomBrowser();
string s = browser.GetWebpage("http://localhost:8781/WebSite3/Default3.aspx");
Response.Write(s);