开发环境:VS2010
VS2010已经集成了Routing组件,在ASP.NET MVC中,我们通过URLRouting实现了Controller,Action的URL控制。在WEBForm中,同样可以!马上开始。
首先,打开VS2010新建一个VS2010webForm,命名为(UrlTest),首先我们为网站添加System.Web.Routing引用,如图
好,引用添加好了。
第二步,我们在Global.asax中添加,RouteCollection的注册,关键代码如下:
注:先Global.asax中添加一下引用<%@ Import Namespace="System.Web.Routing" %>
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(
"DefaultRoute",
"Default/{id}.html",
"~/Default.aspx");
}
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
// 在应用程序启动时运行的代码
}
现在我们已经注册了一个Route,对Default/{id}.html,映射到Default.aspx,这样我们在Default.aspx只要通过RouteData对象,获取值,键为id的参数即可。
那么在Default.aspx.cs里面我们写入以下代码:
if (RouteData.Values["id"] != null)
{
Response.Write("<h1>" + RouteData.Values["id"].ToString() + "</h1>");
}
好了,简单吧!运行程序输入Url http://localhost:9801/UrlTest/Default/123.html
效果如图所示:
看到URL地址了吧,还有页面左上角的”123“了吧。
当然要发布到IIS,记得配置下映射哦。