如何获得Stack Overflow等干净的URL?

时间:2009-06-23 21:08:45

标签: .net architecture url-routing httphandler

在某些.NET驱动的网站上,网址不以asp.net网页名称结尾,例如default.aspx,而是使用模式http://sitename.comhttp://sitename.com/subdirectory/subdirectory。该站点被映射为根目录下的子目录,即。 / tags,/ users,/ badges,URL分别是/ tags,/ users,/ badges。

使用特定示例的Stack Overflow使用How do get clean URLs like Stackoverflow?形式的问题URL。这是优化搜索引擎页面的好方法。

这是使用HTTP处理程序实现的吗? GET请求是否根据路径进行过滤,整个响应是根据问题ID在处理程序本身中形成的?还有其他人在乎推测?

5 个答案:

答案 0 :(得分:23)

它是ASP.Net MVC,它内置了.Net路由。路由也适用于非MVC项目,但

http://msdn.microsoft.com/en-us/library/cc668201.aspx

这只是一个.dll你可以放在bin文件夹中。基本上它使用正则表达式来匹配您的URL与页面/模板。

答案 1 :(得分:18)

这是通过Apache中的mod_rewriteurl_rewriting on IIS的类似方法实现的。

注意:SOFlow使用后者。

答案 2 :(得分:5)

REST principles之后,网址采用该格式,其中所有内容都是具有唯一网址的资源。

我想我在博客的某个地方读到这是通过使用ASP.NET MVC framework来实现的。

答案 3 :(得分:3)

我知道Stack Overflow正在使用ASP.NET MVC框架,它可能内置了一个URL重写系统。对于非Windows系统,Apache mod_rewrite很常见。

例如,维基页面:http://server.com/wiki/Main_Page请求由网络服务器处理。它被翻译成/wiki/index.php?page=Main_Page

以下是Apache中URL重写的一个示例:

RewriteEngine on
RewriteRule ^forum-([0-9]+)\.html$ forumdisplay.php?fid=$1 [L,QSA]
RewriteRule ^forum-([0-9]+)-page-([0-9]+)\.html$ forumdisplay.php?fid=$1&page=$2 [L,QSA]

RewriteRule ^thread-([0-9]+)\.html$ showthread.php?tid=$1 [L,QSA]
RewriteRule ^thread-([0-9]+)-page-([0-9]+)\.html$ showthread.php?tid=$1&page=$2 [L,QSA]

这就是说,如果输入的网址是forum-##.html,那么就像处理forumdisplay.php?fid=##一样处理该请求。 thread-##.html规则也是如此。

答案 4 :(得分:0)

您可以使用Context.RewritePath在ASP.net中执行此操作。

Global.asax 中,创建一个Application.BeginRequest事件处理程序。

例如,如果您想提出

的请求
example.com/questions

实际上从

返回结果
example.com/Questions/Default.aspx

<强> Global.asax中

<%@ Application Language="C#" %>
<script runat="server">

   void Application_BeginRequest(Object sender, EventArgs e)
   {
       string originalPath = HttpContext.Current.Request.Path.ToLower();

       if (originalPath.Contains("/questions"))
       {
           String newPath = originalPath.Replace("/questions", "/Questions/Questions.aspx");
           Context.RewritePath(newPath);
       }
    }
</script>

如果您的网站在.NET Framework 4之前运行任何内容,则必须手动打开 web.config 中的runAllManagedModulesForAllRequests,否则 BeginRequest 事件不会被解雇:

<configuration>
...
   <system.webServer>
      <modules runAllManagedModulesForAllRequests="true" />
   </system.webServer>
</configuration>
相关问题