• ASP.NET WebForm路由模拟


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

    2014-11-08 11:49 by 郝喜路, 232 阅读, 0 评论, 收藏编辑

          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

    image

       二、添加一个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页面的内容。

    image

    仅仅在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
                        {
                            
                        }
                    }
    
                }
            }
    复制代码
    image


    作者:郝喜路  
    出处:http://haoxilu.cnblogs.com/ 

  • 相关阅读:
    Mybatis学习(3)实现数据的增删改查
    Mybatis学习(2)以接口的方式编程
    Mybatis学习(1)开发环境搭建
    Apache Commons 工具类介绍及简单使用
    JAVA枚举使用详解
    Spring中的<context:annotation-config/>配置
    SpringMVC(12)完结篇 基于Hibernate+Spring+Spring MVC+Bootstrap的管理系统实现
    SpringMVC(11)表单标签
    面试题
    开发辅助网址
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/4085624.html
Copyright © 2020-2023  润新知