熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

Asp.Net中動態頁面轉靜態頁面

2013-11-13 10:51:47  來源: .NET編程 

  關於在AspNet中動態頁面轉靜態頁面的方法網上比較多結合實際的需求我在網上找了一些源代碼並作修改現在把修改後的代碼以及說明寫一下

  一個是一個頁面轉換的類該類通過靜態函數Changfile()來實現動態頁面到靜態頁面的轉換

using System;
using SystemData;
using SystemConfiguration;
using SystemWeb;
using SystemWebSecurity;
using SystemWebUI;
using SystemWebUIWebControls;
using SystemWebUIWebControlsWebParts;
using SystemWebUIHtmlControls;
using SystemText;
using SystemIO;

/**//// <summary>
/// Summary description for HtmlProxy
/// </summary>
public class HtmlProxy
{
public HtmlProxy()
{
}
public static bool ChangeFile(int id)
{
string filename = HttpContextCurrentServerMapPath(Post_ + id + html);
//嘗試讀取已有文件
Stream st = GetFileStream(filename);
//如果文件存在並且讀取成功
if (st != null)
{
using (st)
{
StreamToStream(st HttpContextCurrentResponseOutputStream);
return true;
//ResponseEnd();
}
}
else
{
StringWriter sw = new StringWriter();
HttpContextCurrentServerExecute(ForumDetailaspx?PID= + id sw);

string content = swToString();
//寫進文件
try
{
using (FileStream fs = new FileStream(filename FileModeCreate FileAccessWrite FileShareWrite))
{
using (StreamWriter stw = new StreamWriter(fs HttpContextCurrentResponseContentEncoding))
{
stwWrite(content);
}
}
 return true;
}
catch { return false; }
}
}

private static Stream GetFileStream(string filename)
{
try
{
DateTime dt = FileGetLastWriteTime(filename);
TimeSpan ts = dt DateTimeNow;
if (tsTotalHours >)
{
//一小時後過期
return null;
}
return new FileStream(filename FileModeOpen FileAccessRead FileShareRead);
}
catch { return null; }
}
static public void StreamToStream(Stream src Stream dst)
{
  byte[] buf = new byte[];
  while (true)
{
int c = srcRead(buf bufLength);
if (c == )
return;
dstWrite(buf c);
 }
 }
}
  在頁面文件中ForURLaspx的後台代碼如下
protected void Page_Load(object sender EventArgs e)
{
try
{
int id = intParse(RequestQueryString[PID]);
if(HtmlProxyChangeFile(id))
{
 ResponseRedirect(Post_ + id + html);
}
 else
{
 ResponseRedirect(Postaspx?PID= + id );
}
}
 catch {
}
}


From:http://tw.wingwit.com/Article/program/net/201311/14656.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.