一 什么是url重写
URL 重写是截取传入 Web 请求并自动将请求重定向到其他 URL 的过程。比如浏览器发来请求 hostname/101.aspx ,服务器自动将这个请求中定向为http://hostname/list.aspx ?id=101。 会人为改为 hostname/101.shtml
url重写的优点在于:
l    缩短url,隐藏实际路径提高安全性
l    易于用户记忆和键入。 
l    易于被搜索引擎收录

二 实现url重写的基本方法
1. 创建类项目UrlRewriter,项目中增加三个类URLRewriter.Config.cs,URLRewriter.Form.cs,URLRewriter.Module.cs

  1. using System;
  2. using System.Configuration;
  3. using System.Collections;
  4.  
  5. namespace URLRewriter.Config
  6. {
  7. // Define a custom section containing a simple element and a collection of the same element.
  8. // It uses two custom types: UrlsCollection and UrlsConfigElement.
  9. public class UrlsConfig
  10. {
  11. public static UrlsSection GetConfig()
  12. {
  13. return (UrlsSection)System.Configuration.ConfigurationManager.GetSection("CustomConfiguration");
  14. }
  15.  
  16. }
  17.  
  18. public class UrlsSection : ConfigurationSection
  19. {
  20. [ConfigurationProperty("urls",IsDefaultCollection = false)]
  21. public UrlsCollection Urls
  22. {
  23. get
  24. {
  25. return (UrlsCollection)this["urls"];
  26. }
  27. }
  28. }
  29.  
  30. // Define the UrlsCollection that contains UrlsConfigElement elements.
  31. public class UrlsCollection : ConfigurationElementCollection
  32. {
  33. protected override ConfigurationElement CreateNewElement()
  34. {
  35. return new UrlConfigElement();
  36. }
  37. protected override Object GetElementKey(ConfigurationElement element)
  38. {
  39. return ((UrlConfigElement)element).VirtualUrl;
  40. }
  41.  
  42. public UrlConfigElement this[int index]
  43. {
  44. get
  45. {
  46. return (UrlConfigElement)BaseGet(index);
  47. }
  48. }
  49.  
  50. }
  51.  
  52. // Define the UrlConfigElement.
  53. public class UrlConfigElement : ConfigurationElement
  54. {
  55.  
  56. [ConfigurationProperty("virtualUrl", IsRequired = true)]
  57. public string VirtualUrl
  58. {
  59. get
  60. {
  61. return (string)this["virtualUrl"];
  62. }
  63. set
  64. {
  65. this["virtualUrl"] = value;
  66. }
  67. }
  68.  
  69. [ConfigurationProperty("destinationUrl", IsRequired = true)]
  70. public string DestinationUrl
  71. {
  72. get
  73. {
  74. return (string)this["destinationUrl"];
  75. }
  76. set
  77. {
  78. this["destinationUrl"] = value;
  79. }
  80. }
  81. }
  82. }
  83.  
  84. using System;
  85. using System.Data;
  86. using System.Configuration;
  87. using System.Web;
  88. using System.Web.Security;
  89. using System.Web.UI;
  90. using System.Web.UI.WebControls;
  91. using System.Web.UI.WebControls.WebParts;
  92. using System.Web.UI.HtmlControls;
  93.  
  94. /// <summary>
  95. /// FormRewriter 的摘要说明
  96. /// </summary>
  97. namespace URLRewriter.Form
  98. {
  99. public class FormRewriterControlAdapter : System.Web.UI.Adapters.ControlAdapter
  100. {
  101. public FormRewriterControlAdapter()
  102. {
  103. }
  104.  
  105. protected override void Render(HtmlTextWriter writer)
  106. {
  107. base.Render(new RewriteFormHtmlTextWriter(writer));
  108. }
  109. }
  110.  
  111. public class RewriteFormHtmlTextWriter : HtmlTextWriter
  112. {
  113. public RewriteFormHtmlTextWriter(HtmlTextWriter writer)
  114. : base(writer)
  115. {
  116. base.InnerWriter = writer.InnerWriter;
  117. }
  118. public RewriteFormHtmlTextWriter(System.IO.TextWriter writer)
  119. : base(writer)
  120. {
  121. base.InnerWriter = writer;
  122. }
  123.  
  124. public override void WriteAttribute(string name, string value, bool fEncode)
  125. {
  126. //If the attribute we are writing is the "action" attribute, and we are not on a sub-control,
  127. //then replace the value to write with the raw URL of the request - which ensures that we'll
  128. //preserve the PathInfo value on postback scenarios
  129. if (name == "action")
  130. {
  131. HttpContext context = HttpContext.Current;
  132. if (context.Items["ActionAlreadyWritten"] == null)
  133. {
  134. //We will use the Request.RawUrl property within ASP.NET to retrieve the origional
  135. //URL before it was re-written.
  136. value = context.Request.RawUrl;
  137. //Indicate that we've already rewritten the <form>'s action attribute to prevent
  138. //us from rewriting a sub-control under the <form> control
  139. context.Items["ActionAlreadyWritten"] = true;
  140. }
  141. }
  142. base.WriteAttribute(name, value, fEncode);
  143. }
  144. }
  145.  
  146. }
  147.  
  148. using System;
  149. using System.Web;
  150. using System.Text.RegularExpressions;
  151. using System.Configuration;
  152. using URLRewriter.Config;
  153.  
  154. namespace URLRewriter
  155. {
  156. public class RewriterModule : IHttpModule
  157. {
  158. public void Init(HttpApplication app)
  159. {
  160. // WARNING! This does not work with Windows authentication!
  161. // If you are using Windows authentication, change to app.BeginRequest
  162. app.AuthorizeRequest += new EventHandler(this.URLRewriter);
  163. }
  164.  
  165. protected void URLRewriter(object sender, EventArgs e)
  166. {
  167. HttpApplication app = (HttpApplication) sender;
  168. string requestedPath = app.Request.Path;
  169.  
  170. // get the configuration rules
  171. UrlsCollection rules = UrlsConfig.GetConfig().Urls;
  172.  
  173. for (int i = ; i < rules.Count; i++)
  174. {
  175. // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
  176. string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].VirtualUrl) + "$";
  177.  
  178. Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
  179. if (re.IsMatch(requestedPath))
  180. {
  181. string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].DestinationUrl));
  182. RewriterUtils.RewriteUrl(app.Context, sendToUrl);
  183. break;
  184. }
  185. }
  186.  
  187. }
  188.  
  189. public void Dispose() { }
  190. }
  191.  
  192. /// <summary>
  193. /// Provides utility helper methods for the rewriting HttpModule and HttpHandler.
  194. /// </summary>
  195. /// <remarks>This class is marked as internal, meaning only classes in the same assembly will be
  196. /// able to access its methods.</remarks>
  197. internal class RewriterUtils
  198. {
  199. #region RewriteUrl
  200. /// <summary>
  201. /// Rewrite's a URL using <b>HttpContext.RewriteUrl()</b>.
  202. /// </summary>
  203. /// <param name="context">The HttpContext object to rewrite the URL to.</param>
  204. /// <param name="sendToUrl">The URL to rewrite to.</param>
  205. internal static void RewriteUrl(HttpContext context, string sendToUrl)
  206. {
  207. string x, y;
  208. RewriteUrl(context, sendToUrl, out x, out y);
  209. }
  210.  
  211. /// <summary>
  212. /// Rewrite's a URL using <b>HttpContext.RewriteUrl()</b>.
  213. /// </summary>
  214. /// <param name="context">The HttpContext object to rewrite the URL to.</param>
  215. /// <param name="sendToUrl">The URL to rewrite to.</param>
  216. /// <param name="sendToUrlLessQString">Returns the value of sendToUrl stripped of the querystring.</param>
  217. /// <param name="filePath">Returns the physical file path to the requested page.</param>
  218. internal static void RewriteUrl(HttpContext context, string sendToUrl, out string sendToUrlLessQString, out string filePath)
  219. {
  220. // see if we need to add any extra querystring information
  221. if (context.Request.QueryString.Count > )
  222. {
  223. if (sendToUrl.IndexOf('?') != -)
  224. sendToUrl += "&" + context.Request.QueryString.ToString();
  225. else
  226. sendToUrl += "?" + context.Request.QueryString.ToString();
  227. }
  228.  
  229. // first strip the querystring, if any
  230. string queryString = String.Empty;
  231. sendToUrlLessQString = sendToUrl;
  232. if (sendToUrl.IndexOf('?') > )
  233. {
  234. sendToUrlLessQString = sendToUrl.Substring(, sendToUrl.IndexOf('?'));
  235. queryString = sendToUrl.Substring(sendToUrl.IndexOf('?') + );
  236. }
  237.  
  238. // grab the file's physical path
  239. filePath = string.Empty;
  240. filePath = context.Server.MapPath(sendToUrlLessQString);
  241.  
  242. // rewrite the path
  243. context.RewritePath(sendToUrlLessQString, String.Empty, queryString);
  244. }
  245. #endregion
  246.  
  247. /// <summary>
  248. /// Converts a URL into one that is usable on the requesting client.
  249. /// </summary>
  250. /// <remarks>Converts ~ to the requesting application path. Mimics the behavior of the
  251. /// <b>Control.ResolveUrl()</b> method, which is often used by control developers.</remarks>
  252. /// <param name="appPath">The application path.</param>
  253. /// <param name="url">The URL, which might contain ~.</param>
  254. /// <returns>A resolved URL. If the input parameter <b>url</b> contains ~, it is replaced with the
  255. /// value of the <b>appPath</b> parameter.</returns>
  256. internal static string ResolveUrl(string appPath, string url)
  257. {
  258. if (url.Length == || url[] != '~')
  259. return url; // there is no ~ in the first character position, just return the url
  260. else
  261. {
  262. if (url.Length == )
  263. return appPath; // there is just the ~ in the URL, return the appPath
  264. if (url[] == '/' || url[] == '//')
  265. {
  266. // url looks like ~/ or ~/
  267. if (appPath.Length > )
  268. return appPath + "/" + url.Substring();
  269. else
  270. return "/" + url.Substring();
  271. }
  272. else
  273. {
  274. // url looks like ~something
  275. if (appPath.Length > )
  276. return appPath + "/" + url.Substring();
  277. else
  278. return appPath + url.Substring();
  279. }
  280. }
  281. }
  282. }
  283.  
  284. }
  1. .在web.config里设置如下:
  2.  
  3. Code
  4. <?xml version="1.0"?>
  5. <configuration>
  6. <configSections>
  7. <section name="CustomConfiguration" type="URLRewriter.Config.UrlsSection, URLRewriter" />
  8. </configSections>
  9.  
  10. <CustomConfiguration>
  11. <urls>
  12. <add virtualUrl="~/microsoft*.*" destinationUrl="~/default.aspx?id=abc" />
  13. <add virtualUrl="~/microsoft*" destinationUrl="~/default.aspx" />
  14. <add virtualUrl="~/m/i/c/rosoft.aspx" destinationUrl="~/default.aspx" />
  15.  
  16. <add virtualUrl="~/cc*.*" destinationUrl="~/default2.aspx?id=11" />
  17. </urls>
  18. </CustomConfiguration>
  19.  
  20. <system.web>
  21. <httpModules>
  22. <add type="URLRewriter.RewriterModule, URLRewriter" name="RewriterModule"/>
  23. </httpModules>
  24. <authentication mode="Forms"/>
  25. </system.web>
  26. </configuration>
  27.  
  28. .处理回发
  29. 在重写后的url里如果产生回发,例如有一个按钮,又调用了该被重写的aspx,用户浏览器中将会显示该aspx文件实际的地址,也就是http://hostname/default.aspx?id=11。但从用户的角度考虑,如 果单击按钮时突然看到 URL 更改会使他们感到不安。因此必须解决这个问题。
  30. 自己定义一个Actionlessform类,在aspx中不再使用系统提供的form 标记
  31.  
  32. Code
  33. using System;
  34. using System.Web.UI;
  35. using System.Web.UI.WebControls;
  36. using System.ComponentModel;
  37.  
  38. namespace ActionlessForm
  39. {
  40. /// <summary>
  41. /// The Form class extends the HtmlForm HTML control by overriding its RenderAttributes()
  42. /// method and NOT emitting an action attribute.
  43. /// </summary>
  44. public class Form : System.Web.UI.HtmlControls.HtmlForm
  45. {
  46. /// <summary>
  47. /// The RenderAttributes method adds the attributes to the rendered <form> tag.
  48. /// We override this method so that the action attribute is not emitted.
  49. /// </summary>
  50. protected override void RenderAttributes(HtmlTextWriter writer)
  51. {
  52. // write the form's name
  53. writer.WriteAttribute("name", this.Name);
  54. base.Attributes.Remove("name");
  55.  
  56. // write the form's method
  57. writer.WriteAttribute("method", this.Method);
  58. base.Attributes.Remove("method");
  59.  
  60. // remove the action attribute
  61. base.Attributes.Remove("action");
  62.  
  63. // finally write all other attributes
  64. this.Attributes.Render(writer);
  65.  
  66. if (base.ID != null)
  67. writer.WriteAttribute("id", base.ClientID);
  68. }
  69.  
  70. }
  71. }
  72.  
  73. 创建此类并对其进行编译之后,要在 ASP.NET Web 应用程序中使用它,应首先将其添加到 Web 应用程序的 References 文件夹中。然后,要 使用它来代替 HtmlForm 类,做法是在 ASP.NET 网页的顶部添加以下内容:
  74.  
  75. <%@ Register TagPrefix="af" Namespace="ActionlessForm" Assembly="ActionlessForm" %>

Url地址重写的更多相关文章

  1. php url地址重写

    地址重写: urlRewrite: 就是:  1. 将php的地址index.php不写只写Action模块和function方法, 或者 2. php地址转变成html地址, 就是一种假的html, ...

  2. Nginx 的编译安装和URL地址重写

    本文转自:http://www.178linux.com/14119#rd?sukey=ecafc0a7cc4a741b573a095a3eb78af6b4c9116b74d0bbc9844d8fc5 ...

  3. Magento 自定义URL 地址重写 分类分级显示

    我们打算将URL在分类页面和产品页面分别定义为: domain.com/category/分类名.html domain.com/category/子分类名.html domain.com/goods ...

  4. Apache Nginx URL 地址 重写

    URL重写这东西在工作中用了很多次了,但每次都忘记了要记得把知道的积累下来. 哎,要么认为没必要,要么就是没时间?! 一.Apache 篇 官方地址:http://man.chinaunix.net/ ...

  5. springboot中url地址重写(urlwrite)

    在日常网站访问中,会把动态地址改造成伪静态地址. 例如: 访问新闻栏目 /col/1/,这是原有地址,如果这样访问,不利于搜索引擎检索收录,同时安全性也不是很好. 改造之后: /col/1.html. ...

  6. URL地址重写例子(Helicon)

    # Helicon ISAPI_Rewrite configuration file# Version 3.1.0.86 #RewriteEngine on RewriteRule ^/esf/.+( ...

  7. 【转载】ASP.NET MVC重写URL制作伪静态网页,URL地址以.html结尾

    在搜索引擎优化领域,静态网页对于SEO的优化有着很大的好处,因此很多人就想把自己的网站的一些网页做成伪静态.我们现在在网络上发现很多博客网站.论坛网站.CMS内容管理系统等都有使用伪静态这一种情况,伪 ...

  8. 解决URL中包含“%2F”导致Apache地址重写mod_rewrite失效的问题

    在使用Apache地址重写mod_rewrite期间,发现,当URL和PATH_INFO中出现%2f(/)或者%5c(\), 会被认为这是个不合法的请求, Apache将会直接返回"404 ...

  9. IIS:URL Rewrite实现vue的地址重写

    vue-router 全局配置 const router = new VueRouter({ mode: 'history', routes: [...] }) URL Rewrite 1.添加规则 ...

随机推荐

  1. Navicat系列产品激活教程

    准备 本教程可破解12.x版本,如果教程失效请联系我 # 19.1.11 破解暂时失效,请勿更新 (如已更新请卸载重新安装老版本,数据不会丢失 http://download.navicat.com/ ...

  2. 34)django-上传文件,图片预览功能实现

    目录 文件上传      1)form表单提交上传(会刷新)      2)ajax上传      3)iframe      4)图片上传预览(思路保存文件的时候,把文件保存文件的路径反馈回,客户端 ...

  3. python与用户交互、数据类型

    一.与用户交互 1.什么是用户交互: 程序等待用户输入一些数据,程序执行完毕反馈信息. 2.如何使用 在python3中使用input,input会将用户输入的如何内容存为字符串:在python中分为 ...

  4. liux三剑客grep 正则匹配

    001正则匹配(大部分需要转义) ‘^‘: 锚定行首 '$' : 锚定行尾 [0-9] 一个数字 [^0-9] 除去数字所有,^出现在[]这里表示取反 [a-z] [A-Z] [a-Z] \s 匹配空 ...

  5. linux学习之uniq

    uniq最经常用的是统计次数,通常先排序,然后uniq  -c cat a.txt |sort -nr |uniq -c

  6. Java的动手动脑(五)

    日期:2018.11.1 星期四 博客期:021 Part1: 运行代码 class Grandparent { public Grandparent() { System.out.println(& ...

  7. bs4

  8. linux安装MongoDB

    安装 32bit的mongodb最大只能存放2G的数据,64bit就没有限制 到官网,选择合适的版本下载,本次下载3.4.0版本 解压 tar -zxvf mongodb-linux-x86_64-u ...

  9. Python - 去除list中的空字符

    list1 = ['122', '2333', '3444', '', '', None] a = list(filter(None, list1)) # 只能过滤空字符和None print(a) ...

  10. C#线性表

    线性表是线性结构的抽象 线性结构的特点是结构中的数据元素之间存在一对一的线性关系 一对一的关系指的是数据元素之间的位置关系 (1)除第一个位置的数据元素外,其它数据元素位置的前面都只有一个数据元素 ( ...