.net 4.0(C#) 路由route实现首页用域名或伪静态访问
.net 4.0 增加了一个新的地址重写功能,就通过路由(route)来重写Url,从而实现伪静态。使用这个方法需要把要重写的地址注册到路由表中,注册需要在 Global 文件中完成。
使用 .net 4.0 route 功能可以实现网站的每一页地址重写,至于重写什么地址可由自己决定,既可重写为带 html 扩展名的伪静态Url,也可以重写为不带扩展名的Url。假如要把首页重写为只用域名或伪静态能够访问(用 default.aspx 或 index.aspx 无法访问),只需把这个路径添加到路由表就能实现。
net 4.0(C#) 路由route实现地址重写主要用 MapPageRoute() 方法实现,只需把要重写的网页通过此方法添加到路由表就行了。以下为用 route 实现网站首页只用域名访问和用伪静态(index.htm)访问的两个例子。
一、.net 4.0(C#) 路由route实现首页只能用域名访问
只需在 Global 文件中把网站首页的路径添加到路由表即可,具体代码如下:
using System;
using System.Web;
using System.Web.SessionState;
using System.Web.Routing;
namespace RouteEg
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object MapPageRoute, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("homepage", "", "~/default.aspx");
}
}
}
MapPageRoute() 方法,第一个参数为 routeName(路由名称),第二参数为 routeUrl(重写后的地址),第三个参数为physicalFile(要重写的物理路径,如网站主页 ~/default.aspx)。需要注意的是:把首页重写只能用域名访问,第二个参数留空即可。
二、net 4.0(C#) 路由route实现首页用伪静态访问
方法跟只能用域名访问是一样的,只是第二个参数不能再留空,而用 index.html,此外还需要在网站配置文件(Web.config)中添加 <modules runAllManagedModulesForAllRequests="true" />,完整代码如下:
using System;
using System.Web;
using System.Web.SessionState;
using System.Web.Routing;
namespace RouteEg
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object MapPageRoute, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("homepage", "index.html", "~/default.aspx");
}
}
}
在网站配置文件(Web.config)中添加:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>