2009-10-19 136 views

回答

5

为客户端

在Internet Explorer

右键单击浏览器 - >查看源代码

在Firefox

右键单击浏览器 - >查看页面来源

服务器端

您可以覆盖页面的呈现方法来捕获服务器端的HTML源代码。

protected override void Render(HtmlTextWriter writer) 
{ 
    // setup a TextWriter to capture the markup 
    TextWriter tw = new StringWriter(); 
    HtmlTextWriter htw = new HtmlTextWriter(tw); 

    // render the markup into our surrogate TextWriter 
    base.Render(htw); 

    // get the captured markup as a string 
    string pageSource = tw.ToString(); 

    // render the markup into the output stream verbatim 
    writer.Write(pageSource); 

    // remove the viewstate field from the captured markup 
    string viewStateRemoved = Regex.Replace(pageSource, 
     "<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\".*?\" />", 
     "", RegexOptions.IgnoreCase); 

    // the page source, without the viewstate field, is in viewStateRemoved 
    // do what you like with it 
} 
+0

你错过了服务器客户端 - 第二次运行时包含HttpRequest和HttpResponse – cjk 2009-10-19 12:39:52

+0

:) – solairaja 2009-10-19 12:48:03

2

重写渲染方法并使用自己的HtmlWriter调用base.Render。

+0

有没有办法使用Request.Url获取当前页面的html? – Constantine 2009-10-21 11:51:47

+0

什么意思是“使用Request.Url的当前页面”? – 2009-10-21 12:35:43

1

真的要解析HTML?这是一个棘手的业务。如果你不一定要这样做,我会通过在客户端使用DOM方法(如果客户端解决方案是可接受的)来避免它。如果你正在做lot它,你可能会考虑jQuery,Prototype,或其他一些工具来帮助。