12.URL重写

  • 为什么要URL重写?1.有利于SEO(搜索引擎优化),带参数的RUL权重较低。2.地址看起来更正规,推广uid. 如我们一般在访问网页是会带参数,http://aaa.com/view.htm?id=1...,用URL重写后可以这样访问http://aaa.com/view-1.htm就可以访问参数id=1的页面,但实际上view-1.htm是不存在的,这个处理是在全局文件的Application_BeginRequest 事件 中处理后导向id=1的页面的。
  • 伪静态:看起来像普通页面,而非动态生成的页面。
  • 原理:在Global.asax的Application_BeginRequest中读取Request.Url得到请求的URL(View-3.aspx),然后用HttpContext.Current.RewritePath(ReWriteUrl)进行重写(View.aspx?id=3格式)
  • 也可以使用微软的URLRewrite,只要修改配置文件就可以进行URL重写。
  • 检查一个网站被SEO保存了搜索页多少次,可以在百度或google中输入site:(域名)例如(site:sina.com)查看被seo的次数。

示例:

   分别建立两个页面,一个为view.htm,另一个为WebForm1.aspx,当我们在客户端输入http://localhot:8080/view-1.aspx是就访问view.htm页面,如果是view-2.aspx时就访问WebForm1.aspx页面。

开发步骤:

  1.建立view.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>

   <a href="http://www.sina.com">新浪</a>

</body>
</html>

  2.建立一WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Global.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
    
    </div>
    </form>
</body>
</html>

  3.添加Global.asax文件,并写入以下事件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Text.RegularExpressions;

namespace Global
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
          //在客户端输入view-1.aspx或view-2.aspx分别重定位到相关的页面处理 
            Regex reg = new Regex(@".+view-(d+).aspx");
            var match = reg.Match(HttpContext.Current.Request.Url.AbsolutePath);
            if (match.Success)
            {
                string id = match.Groups[1].Value;
                if (id == "1")
                    HttpContext.Current.RewritePath("view.htm");
                else
                    HttpContext.Current.RewritePath("WebForm1.aspx");
            }
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}

4.运行截图

  

 

  

原文地址:https://www.cnblogs.com/yagzh2000/p/3174954.html