码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET页面静态化 之 (伪静态)

时间:2014-07-20 23:34:43      阅读:439      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   os   

1.页面为何要静态化

有利于搜索引擎优化(SEO)
使页面URL看起来更正规
真静态 的效率更高,并且更安全,HTML页面不会受Asp.Net相关漏洞的影响;

2.伪静态原理

其原理就是,在一个页面请求的执行期间将伪静态的URL重写成真实的URL路径;

3.那种条件下需要静态化

一个页面经常被访问,并且页面内容基本不变的;
所有用户访问的页面内容基本一样的。
例如:(新闻模块)

4.下面开始带领大家写一个伪静态的案例(新闻模块)

(1)先创建新闻模块数据库
bubuko.com,布布扣
T_Channels表,存储新闻类别
T_FilterWords表,存储评论的过滤词
T_new表,存储新闻信息
T_Review表,存储回复信息
(2)建表SQL语句
USE [WordFilter]
GO
/****** Object:  Table [dbo].[T_Review]    Script Date: 07/20/2014 18:27:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[T_Review](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[body] [nvarchar](max) NULL,
	[nid] [int] NOT NULL,
	[Isvisable] [bit] NULL,
 CONSTRAINT [PK_T_Review] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[T_new]    Script Date: 07/20/2014 18:27:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[T_new](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[title] [nvarchar](50) NULL,
	[body] [nvarchar](max) NULL,
	[chahhelid] [int] NULL,
	[ntime] [datetime] NULL,
 CONSTRAINT [PK_T_new] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[T_FilterWords]    Script Date: 07/20/2014 18:27:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[T_FilterWords](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[WordPattern] [nvarchar](50) NULL,
	[ReplaceWord] [nvarchar](50) NULL,
 CONSTRAINT [PK_T_FilterWords] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object:  Table [dbo].[T_Channels]    Script Date: 07/20/2014 18:27:02 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[T_Channels](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[ParentId] [int] NOT NULL,
	[Name] [nvarchar](50) NULL,
 CONSTRAINT [PK_T_Channels] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

(3)字段解释
数据库名:WordFilter
表名:T_Channels
序号 列名 数据类型 长度 小数位 标识 主键 外键 允许空 默认值 说明
1 Id int 4 0      主键,自增
2 ParentId int 4 0           父级类别id
3 Name nvarchar 50 0           类别名称
表名:T_FilterWords
序号 列名 数据类型 长度 小数位 标识 主键 外键 允许空 默认值 说明
1 id int 4 0       主键,自增
2 WordPattern nvarchar 50 0           过滤词
3 ReplaceWord nvarchar 50 0           替换词
表名:T_new
序号 列名 数据类型 长度 小数位 标识 主键 外键 允许空 默认值 说明
1 id int 4 0       主键,自增
2 title nvarchar 50 0           新闻标题
3 body nvarchar 0 0           新闻内容
4 chahhelid int 4 0           类别id
5 ntime datetime 8 3           发布时间
表名:T_Review
序号 列名 数据类型 长度 小数位 标识 主键 外键 允许空 默认值 说明
1 id int 4 0       主键自增
2 body nvarchar 0 0           评论内容
3 nid int 4 0           新闻id
4 Isvisable bit 1 0           是否显示

(4)创建项目
bubuko.com,布布扣
Common:全局公用类库文件;
WordFilter:显示层代码库;
WordFilter.BLL:BLL代码层库
WordFilter.DAL:DAL代码类库
WordFilter.Model:Model代码类库
(5)创建新闻列表:
        <asp:Repeater ID="news" runat="server">
            <ItemTemplate>
            <li><a href=‘Article-<%#DataBinder.Eval(Container.DataItem, "id")%>.aspx‘><%#DataBinder.Eval(Container.DataItem, "title")%></a></li>
            </ItemTemplate>
        </asp:Repeater>

news.DataSource = new BLL.T_new().GetAllList().Tables[0];
news.DataBind();
(6)创建新闻页
    <script src="/js/xheditor/xheditor-1.1.14-zh-cn.min.js" type="text/javascript"></script>
    <script src="/js/xheditor/xheditor_plugins/ubb.min.js" type="text/javascript"></script>
    <script src="/js/xheditor/ubb2html.js" type="text/javascript"></script>
    <script type="text/javascript">
        var url = window.location.host;
        function submitForm() {
            var nid = $("#nid").val();
            var body = $("#pingnew").val();
            $.post("http://" + url + "/Front1/ashx/postCommon.ashx",
                        { nid: nid, body: body },
                       function (data) {
                           if (data == "ok") {
                               var valueli = body;
                               valueli = "<li>" + ubb2html(valueli) + "</li>";
                               $("#pp > ul").append(valueli);
                               $("#pingnew").val("");
                           }
                           else if (data == "mod") {
                               alert("含有审核词,等待管理员审核");
                           }
                           else if (data == "banned") {
                               alert("含有禁用词,请认真填写评论,文明用语");
                           }
                           else {
                               alert("错误");
                           }
                       });
        }


        $(document).ready(function () {
            var nid = $("#nid").val();
            $("#btnPing").click(submitForm);

            $.getJSON("http://" + url + "/Front1/ashx/getNews.ashx?nid=" + nid,
            function (data) {
                $.each(data, function (i, item) {
                    var valueli =  item.body ;
                    valueli = "<li>" + ubb2html(valueli) + "</li>";
                    $("#pp > ul").append(valueli);
                });
            });

            var plugins = {
                Code: { c: 'btnCode', t: '插入代码', h: 1, e: function () {
                    var _this = this;
                    var htmlCode = '<div><select id="xheCodeType"><option value="html">HTML/XML</option><option value="js">Javascript</option><option value="css">CSS</option><option value="php">PHP</option><option value="java">Java</option><option value="py">Python</option><option value="pl">Perl</option><option value="rb">Ruby</option><option value="cs">C#</option><option value="c">C++/C</option><option value="vb">VB/ASP</option><option value="">其它</option></select></div><div><textarea id="xheCodeValue" wrap="soft" spellcheck="false" style="width:300px;height:100px;" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>'; var jCode = $(htmlCode), jType = $('#xheCodeType', jCode), jValue = $('#xheCodeValue', jCode), jSave = $('#xheSave', jCode);
                    jSave.click(function () {
                        _this.loadBookmark();
                        _this.pasteText('[code=' + jType.val() + ']\r\n' + jValue.val() + '\r\n[/code]');
                        _this.hidePanel();
                        return false;
                    });
                    _this.saveBookmark();
                    _this.showDialog(jCode);
                }
                },
                Flv: { c: 'btnFlv', t: '插入Flv视频', h: 1, e: function () {
                    var _this = this;
                    var htmlFlv = '<div>Flv文件:  <input type="text" id="xheFlvUrl" value="http://" class="xheText" /></div><div>宽度高度: <input type="text" id="xheFlvWidth" style="width:40px;" value="480" /> x <input type="text" id="xheFlvHeight" style="width:40px;" value="400" /></div><div style="text-align:right;"><input type="button" id="xheSave" value="确定" /></div>';
                    var jFlv = $(htmlFlv), jUrl = $('#xheFlvUrl', jFlv), jWidth = $('#xheFlvWidth', jFlv), jHeight = $('#xheFlvHeight', jFlv), jSave = $('#xheSave', jFlv);
                    jSave.click(function () {
                        _this.loadBookmark();
                        _this.pasteText('[flv=' + jWidth.val() + ',' + jHeight.val() + ']' + jUrl.val() + '[/flv]');
                        _this.hidePanel();
                        return false;
                    });
                    _this.saveBookmark();
                    _this.showDialog(jFlv);
                }
                }
            }, emots = {
                msn: { name: 'MSN', count: 40, width: 22, height: 22, line: 8 },
                pidgin: { name: 'Pidgin', width: 22, height: 25, line: 8, list: { smile: '微笑', cute: '可爱', wink: '眨眼', laugh: '大笑', victory: '胜利', sad: '伤心', cry: '哭泣', angry: '生气', shout: '大骂', curse: '诅咒', devil: '魔鬼', blush: '害羞', tongue: '吐舌头', envy: '羡慕', cool: '耍酷', kiss: '吻', shocked: '惊讶', sweat: '汗', sick: '生病', bye: '再见', tired: '累', sleepy: '睡了', question: '疑问', rose: '玫瑰', gift: '礼物', coffee: '咖啡', music: '音乐', soccer: '足球', good: '赞同', bad: '反对', love: '心', brokenheart: '伤心'} },
                ipb: { name: 'IPB', width: 20, height: 25, line: 8, list: { smile: '微笑', joyful: '开心', laugh: '笑', biglaugh: '大笑', w00t: '欢呼', wub: '欢喜', depres: '沮丧', sad: '悲伤', cry: '哭泣', angry: '生气', devil: '魔鬼', blush: '脸红', kiss: '吻', surprised: '惊讶', wondering: '疑惑', unsure: '不确定', tongue: '吐舌头', cool: '耍酷', blink: '眨眼', whistling: '吹口哨', glare: '轻视', pinch: '捏', sideways: '侧身', sleep: '睡了', sick: '生病', ninja: '忍者', bandit: '强盗', police: '警察', angel: '天使', magician: '魔法师', alien: '外星人', heart: '心动'} }
            };
            $('#pingnew').xheditor({ plugins: plugins, tools: 'full', showBlocktag: false, forcePtag: false, beforeSetSource: ubb2html, beforeGetSource: html2ubb, emots: emots, emotMark: true, shortcuts: { 'ctrl+enter': submitForm} });

        });
    </script>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <input type="hidden" id="nid" value='<%=nid%>' />
    <h2>
        <%=title%></h2>
    <p>
        <%=body%>
    </p>
    <div style="color: Red;">
        评论区:
    </div>
    <div id="pp">
        <ul>
        </ul>
    </div>
    <div>

            <textarea id="pingnew" name="pingnew"  rows="12" cols="80"></textarea>
        <p>
            <input type="button" id="btnPing" value="提交评论" /></p>

评论通过ajax提交和获取,有助于下一片 的页面真静态教程
public string title;
		protected string body;
		protected int nid;
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				if (Request.QueryString["newid"] != null)
				{
					int newid =int.Parse(Request.QueryString["newid"].ToString());
					nid = newid;
					BindNews(newid);
				}
			}
		}
		protected void BindNews(int newid)
		{
			Model.T_new news = new BLL.T_new().GetModel(newid);
			if (news != null)
			{
				title = news.title;
				body = news.body;
			}
		}

(6)核心
在Global.asax的Application_BeginRequest处理请求的URL
		protected void Application_BeginRequest(object sender, EventArgs e) {
			//获取请求的URL(虚拟路径)
			string url = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath;
			//用正则验证是否符合 @"~/Front1/Article-(\d+)\.aspx"
			Match match = Regex.Match(url, @"~/Front1/Article-(\d+)\.aspx");
			//如果符合此验证
			if (match.Success)
			{
				//获取文章的id
				string id = match.Groups[1].Value;
				//控制服务器执行 下面URL
				HttpContext.Current.RewritePath("~/Front1/Article.aspx?newid="+id);
			}
		}


ASP.NET页面静态化 之 (伪静态),布布扣,bubuko.com

ASP.NET页面静态化 之 (伪静态)

标签:style   blog   http   java   color   os   

原文地址:http://blog.csdn.net/abc456456456456/article/details/37994777

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!