2009-10-19 153 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,或其他一些工具來幫助。