如何从asp.net aspx页面获取当前页面源

Emr*_*tun 1 html c# asp.net

嗨,我正在尝试使用asp.net应用程序获取当前页面源。我找到了一段将html转换为pdf的代码,但是为了将我的页面转换为pdf,我需要获取页面的html代码。如何获得这些字符串?我的简单代码是这样的:

        string sPathToWritePdfTo = Server.MapPath("") + "/pdf_dosya_adi.pdf";

        System.Text.StringBuilder sbHtml = new System.Text.StringBuilder();
        sbHtml.Append("<html>");
        sbHtml.Append("<body>");
        sbHtml.Append("<font size='14'>HTML den PDF çevirme Test</font>");
        sbHtml.Append("<br />");
        sbHtml.Append("Body k?sm?nda yazacak yaz?");
        sbHtml.Append("</body>");
        sbHtml.Append("</html>");

        using (System.IO.Stream stream = new System.IO.FileStream

        (sPathToWritePdfTo, System.IO.FileMode.OpenOrCreate))
        {
            Pdfizer.HtmlToPdfConverter htmlToPdf = new Pdfizer.HtmlToPdfConverter();
            htmlToPdf.Open(stream);
            htmlToPdf.Run(sbHtml.ToString());
            htmlToPdf.Close();
        }
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "friendlypdfname.pdf"));
        HttpContext.Current.Response.ContentType = "application/pdf";

        HttpContext.Current.Response.WriteFile(sPathToWritePdfTo);
        HttpContext.Current.Response.End();
Run Code Online (Sandbox Code Playgroud)

如果我可以从asp.net页面上获取html代码,则将页面的所有行都放入sbHtml.Append(“”); 通过使用for循环代码,这将解决我的问题。

Dar*_*rov 5

一种可能性是使用WebClient将HTTP请求发送到给定页面并获取结果HTML:

using (var client = new WebClient())
{
    string html = client.DownloadString("http://example.com/somepage.aspx");
}
Run Code Online (Sandbox Code Playgroud)

这种方法的缺点是它发送一个额外的HTTP请求。

另一种可能性是将WebForm直接呈现为字符串:

using (var writer = new StringWriter())
{
    Server.Execute("SomePage.aspx", writer);
    string html = writer.GetStringBuilder().ToString();
}
Run Code Online (Sandbox Code Playgroud)