【问题标题】:webbrowser class in asp.net websiteasp.net 网站中的 webbrowser 类
【发布时间】:2012-05-21 15:38:13
【问题描述】:

我有一个需求,需要去一个网页并截屏。

为此,我必须创建一个 ASP.NET,以便用户可以输入网站 URL..

我试图创建一个 web 浏览器控件.. 但后来意识到我无法在 asp.net 网站中创建 web 浏览器控件..

我正在尝试做类似http://pietschsoft.com/post/2008/07/C-Generate-WebPage-Thumbmail-Screenshot-Image.aspx 的事情,有人可以帮助我如何开始,因为我知道我们只能在 Windows 表单中使用 Web 浏览器组件,而不能在网站上使用..

我不确定我的问题是不是太傻了,我错过了什么..有人可以帮助我吗

PS:如果我的问题不清楚,请告诉我。我会尝试更具体!

【问题讨论】:

  • 理论上,你不能简单地包含相关DLL中的控件并在服务器端执行它吗?即使您没有运行客户端应用程序,您仍然应该能够包含所有 DLL 并执行代码。

标签: c# asp.net webbrowser-control


【解决方案1】:

我们需要添加带有线程的网络浏览器,否则我们会得到 无法实例化 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);

【讨论】:

  • 谢谢一百万,我只是应用了您的解决方案,并且效果很好。
  • 我正在运行此代码,但无法让 Print() 执行任何操作。
【解决方案2】:

您可以在 ASP.net 中使用 WebBrowser 控件服务器端。只需添加对 System.Windows.Forms 的引用。

【讨论】:

  • 你做了什么?每当我这样做时,我都会收到一个 Active X 线程错误,并且在修复它时,它会“运行”,但 Print() 什么都不做。 (也不例外。)
【解决方案3】:

您或许可以使用 Web 处理程序文件 (.ashx) 而不是 .aspx。这将允许您在没有网络表单的情况下使用网络浏览器控件。

【讨论】:

    猜你喜欢
    • 2013-10-15
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2012-09-01
    相关资源
    最近更新 更多