一、ASP.NET MVC 路由(一)--- ASP.NET WebForm路由模拟

时间:2023-08-19 18:27:56

ASP.NET WebForm 应用,用户请求的是物理文件,其中包括静态页面和动态页面,在Url中的显示都是服务器中一个物理文件的相对路径。但是ASP.NET MVC就不同了,用户请求的是Controller中一个Action方法,这种请求是通过路由将Url映射到相对的Controller和Action中。

ASP.NET MVC是在Application_Start时,定义了路由的规则,当用户使用规定的路由规则进行访问时,就会通过路由映射的方式实现用户完整的Url访问。下面我们就开始使用Asp.net WebForm进行简单的路由模拟。

一、我们新建一个ASP.NET Empty  Web Application

一、ASP.NET MVC 路由(一)--- ASP.NET WebForm路由模拟

二、添加一个Global.asax文件,并在Application_Start事件中模拟ASP.NET MVC写路由代码。(注:Application_Start 事件是当整个应用程序部署到IIS等服务器,启动应用程序池时执行一次)

protected void Application_Start(object sender, EventArgs e)
{
var defaults = new RouteValueDictionary
{
{"controller","*"},
{"action","*"}
};//定义一个路由字典
RouteTable.Routes.MapPageRoute("defaults", "{controller}/{action}", "~/RouteMapping.aspx", true, defaults);//进行默认的路由映射,在整个模拟路由的过程中,所有的用户请求都将交给RouteMapping.aspx这WebForm页面进行处理。
}

三、用户请求"{controller}/{action}"格式的Url路径,如http://localhost:1673/Abc ,那么将显示Abc.aspx页面的内容。

一、ASP.NET MVC 路由(一)--- ASP.NET WebForm路由模拟

仅仅在Application_Start中配置信息是达不到上图的效果的。上图配置的路由信息仅仅是映射了RouteMapping.aspx这一个页面,要想达到较好的效果,需要对RouteMapping.as页面获取到的"{controller}/{action}"信息进行稍微的处理。

protected void Page_Load(object sender, EventArgs e)
{
string controller = RouteData.Values["controller"] as String;//获取到路由表中的controller数据
//string action = RouteData.Values["action"] as String;
if (!String.IsNullOrEmpty(controller))
{
if (controller == "*")
{
Server.Transfer("Default.aspx");//Url地址如http://localhost:1673/则访问默认页
}
else
{
try
{
Server.Transfer(controller + ".aspx");//使用Server.Transfer进行服务器端重定向,进而显示了controller对应的页面方法。
}
catch
{ }
} }
}
一、ASP.NET MVC 路由(一)--- ASP.NET WebForm路由模拟