Detailed introduction to ASP.NET MVC-routing

零下一度
Release: 2017-05-20 13:35:52
Original
2672 people have browsed it

Understanding the Default Routing Table

When you create a new ASP.NET MVC application, the application has already been configured to use ASP.NET routing .ASP.NET routing is set up in two places.

The first point is to enable ASP.NET routing in your application's Web configuration file (Web.config file). There are four nodes in the configuration file related to routing: sytem.web.httpModules section, system.web.httpHandlers section, system.webserver.modules section, and system.webserver.handlers section. Be especially careful not to delete these nodes as routing will not work without them.

The second point, and the more important point, is to create a routing table in the Global.asax file of the application. The Global.asax file is a special file that contains the information that acts on ASP. NET application lifecycle events. The routing table is created during the application start event.

The file in Listing 1 contains the default Global.asax file for an ASP.NET MVC application.

Code Listing 1 - Global.asax.cs

使用系统; 
使用 System.Collections.Generic; 
使用 System.Linq; 
使用 System.Web; 
使用 System.Web.Mvc; 
使用 System.Web.Routing; 
命名空间 MvcApplication1
{
    //注意:有关启用IIS6或IIS7经典模式的说明,
    请访问http://go.microsoft.com/?LinkId=9394801 
    public class MvcApplication:System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection路由)
        {
            routes.IgnoreRoute( “{resource} .axd / {* pathInfo}”); 
            路线。
                MapRoute( “Default”,                                              // Route name 
                “{controller} / {action} / {id}”,                           //具有参数
                的URL new {controller = “Home”,action =“Index”,id =“” } //参数默认值
            ); 
        }
        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes); 
        }
    }
} //具有参数的URL new {controller = “Home”,action =“Index”,id =“” } //参数defaults); } protected void Application_Start(){RegisterRoutes(RouteTable.Routes); }}} //具有参数的URL new {controller = “Home”,action =“Index”,id =“” }  //参数defaults); } protected void Application_Start(){RegisterRoutes(RouteTable.Routes); }}} } protected void Application_Start(){RegisterRoutes(RouteTable.Routes); }}} } protected void Application_Start(){RegisterRoutes(RouteTable.Routes); }}}
Copy after login

When an MVC application is run for the first time, the Application_Start() method is called. This method then calls the RegisterRoutes() method. The RegisterRoutes() method creates the routing table.

The default routing table contains a single route (named default). The DEFAULT route maps the first part of the URL to the controller name, and the second part of the URL to the controller action. The third part maps to a parameter called ID.

Suppose you enter the following URL in the browser's address bar:

/Homepage/Index/ 3

The default routing maps this URL to the following parameters:

Controller=Homepage

Action = Index

id = 3

When you request the URL /Homepage/Index/3, the following will be executed Code:

HomeController.Index(3)

The default route contains default values ​​for all three parameters. If you do not provide a controller, the controller parameter defaults to the home page. If you don't provide an action, the action parameter defaults to the value indicator. Finally, if you do not provide an ID, the ID parameter defaults to the empty string.

Let’s look at a few examples of how default routing maps URLs to controller actions. Imagine you enter the following URL in the browser address bar:

/首页

Due to the default values ​​of the default routing parameters, entering this URL will call the index() method of the HomeController class in code listing 2.

Code Listing 2 - HomeController.cs

使用 System.Web.Mvc; 
命名空间 MvcApplication1.Controllers 
{ 
    [HandleError] 
    public class HomeController:Controller 
    { 
        public ActionResult Index(string id)
        { 
            return View(); 
        } 
    } 
}
Copy after login

In Code Listing 2, the HomeController class contains a method called Index(), which accepts a parameter called Id. The URL /Home will Will cause the Index() method to be called with an empty string as the value of the Id parameter.

Because of the way the MVC framework calls controller actions, the URL /Home also matches the index() method of the HomeController class in Listing 3.

Code Listing 3 - HomeController.cs (Index action without parameters)

使用 System.Web.Mvc; 
命名空间 MvcApplication1.Controllers 
{ 
    [HandleError] 
    public class HomeController:Controller 
    { 
        public ActionResult Index()
        { 
            return View(); 
        } 
    } 
}
Copy after login

The Index() method in Code Listing 3 does not accept any parameters. URL/Home will result in a call The Index() method. URL /Home/Index/3 will also call this method (Id is ignored).

URL /Home will also match the index() method of the HomeController class in Listing 4.

Code Listing 4 - HomeController.cs (Index action using nullable parameters)

使用 System.Web.Mvc; 
命名空间 MvcApplication1.Controllers 
{ 
    [HandleError] 
    public class HomeController:Controller 
    { 
        public ActionResult Index(int?id)
        { 
            return View(); 
        } 
    } 
}
Copy after login

In Code Listing 4, the index() method has an integer parameter. Because this parameter is a nullable parameter (can have a null value), exponent() can be called without throwing an error.

Finally, calling the Index() method in Listing 5 using the URL /Home will throw an exception because the Id parameter is not a nullable parameter. If you try to call the Index() method, you will get an error like the one shown in Figure 1.

Code Listing 5 - HomeController.cs (index action containing Id parameter)

使用 System.Web.Mvc; 
命名空间 MvcApplication1.Controllers 
{ 
    [HandleError] 
    public class HomeController:Controller 
    { 
        public ActionResult Index(int id)
        { 
            return View(); 
        } 
    } 
}
Copy after login

01 (1).jpg

Figure 01: Calling a controller action that expects parameter values

On the other hand, the URL /Home/Index/3 will work well with the index controller action in Listing 5. A request for /Home/Index/3 will cause a call to index() with an Id method, and the Id value is 3.

The purpose of this tutorial is to provide you with a brief introduction to ASP.NET routing. We took a closer look at the default routing table, which is obtained when you create a new ASP.NET MVC application. You learned how the default routing table maps URLs to controller actions.

2.创建自定义路由

在这篇教程中,你会学习到如何为ASP.NET MVC应用程序添加自定义路由。你会学习如何将Global.asax文件中的默认路由表修改为自定义路由。

对于简单的ASP.NET MVC应用程序,默认的路由表已经可以很好的完成工作了。然而,你可以发现会存在特定的路由需求在这种情况下,你可以创建一个自定义路由。

设想一下,举个例子,你正在创建一个博客应用程序你可能想要像这样处理即将到来的请求:

/存档/ 2009年12月25日

当用户输入这一请求,你想要返回对应于日期2009年12月25日的博客条目。为了处理这种类型的请求,你需要创建一个自定义路由。

代码清单1中的Global.asax包含了一个新的自定义路由,命名为了博客,它处理了类似/存档/条目日期这样的请求。

代码清单1 - Global.asax(含有自定义路由)

使用 System.Web.Mvc; 
使用 System.Web.Routing; 
命名空间 MvcApplication1 
{ 
    public class MvcApplication:System.Web.HttpApplication 
    { 
        public static void RegisterRoutes(RouteCollection routes)
        { 
            routes.IgnoreRoute(“{resource} .axd / {* pathInfo}”); 
            routes.MapRoute(
                “Blog”,                                           //路由名称
                “Archive / {entryDate}”,                            //具有参数
                的URL new {controller = “Archive”,action =“ } //参数defaults
            ); 
            routes.MapRoute(
                “Default”,//路由名称
                “{controller} / {action} / {id}”,//具有参数
                的URL new {controller = “Home”,action =“Index”,id =“” } //参数defaults
            ); 
        } 
        protected void Application_Start()
        { 
            RegisterRoutes(RouteTable.Routes); 
        } 
    } 
} }  //参数defaults); routes.MapRoute(“Default”,//路由名称“{controller} / {action} / {id}”,//具有参数的URL new {controller = “Home”,action =“Index”,id =“” } //参数defaults); } protected void Application_Start(){ RegisterRoutes(RouteTable.Routes); } } } ,//路由名称“{controller} / {action} / {id}”,//具有参数的URL new {controller = “Home”,action =“Index”,id =“” } //参数defaults); } protected void Application_Start(){ RegisterRoutes(RouteTable.Routes); } } } ,                                              //路由名称“{controller} / {action} / {id}”,                           //具有参数的URL new {controller = “Home”,action =“Index”,id =“” } //参数defaults); } protected void Application_Start(){ RegisterRoutes(RouteTable.Routes); } } } //具有参数的URL new {controller = “Home”,action =“Index”,id =“” } //参数defaults); } protected void Application_Start(){ RegisterRoutes(RouteTable.Routes); } } } //具有参数的URL new {controller = “Home”,action =“Index”,id =“” }  //参数defaults); } protected void Application_Start(){ RegisterRoutes(RouteTable.Routes); } } }
Copy after login

添加到路由表中的路由顺序非常重要。我们的新自定义博客路由在现有的默认路由前面。如果你将这个顺序颠倒过来,那么默认路由将总是被调用,而不是自定义路由。

自定义博客路由匹配任何以/存档/作为开始的请求因此,它匹配所有下面的网址:

/存档/ 2009年12月25日

/存档/ 2004年10月6日

/存档/苹果

自定义路由将即将到来的请求映射到名为存档的控制器,并且调用了条目()动作。当调用项()方法时,条目日期作为entryDate参数进行了传递。

代码清单2 - ArchiveController.cs

使用系统; 
使用 System.Web.Mvc; 
命名空间 MvcApplication1.Controllers
{
    public class ArchiveController:Controller
    {
        public string Entry(DateTime entryDate)
        {
            return “您从” + entryDate.ToString())请求了条目。
        }
    }
}
Copy after login

注意到代码清单2中的条目()方法接受一个日期时间类型的参数.MVC框架非常的聪明,足以自动地将URL中的条目日期转换为日期时间值。如果URL中的条目日期参数不能转换为日期时间,将会引发错误(如图1)。

图1 - 转换参数时的错误

02 (1).jpg

这篇教程的目的是演示如何创建自定义路由。你学习了如何在Global.asax中文件的路由表中添加自定义路由,该路由代表着博客条目。我们讨论了如何将对博客条目的请求映射到名为ArchiveController的控制器,和名为项()的控制器动作上。

3.创建路由约束

你可以使用路由约束来限制匹配特定路由的浏览器请求。可以使用正则表达式来指定一个路由约束。

举个例子,假设你已经在Global.asax中文件中定义了一个路由。

代码清单1 - Global.asax.cs

routes.MapRoute(
    “Product”,
    “Product / {productId}”,
    new {controller =“Product”,action =“Details”} 
);
Copy after login

代码清单1包含一个叫做产品的路由。你可以使用产品路由将浏览器请求映射到代码清单2中的ProductController的。

代码清单2 - Controllers \ ProductController.cs

使用 System.Web.Mvc; 
命名空间 MvcApplication1.Controllers 
{ 
    public class ProductController:Controller 
    { 
        public ActionResult Details(int productId)
        { 
            return View(); 
        } 
    } 
}
Copy after login

注意到产品控制器公布的详细信息()动作接受一个叫做的productId的参数。这个参数是一个整数参数。

定义在代码清单1中的路由将会匹配下面的任意网址:

/产品/ 23
/产品/ 7
不幸的是,路由也会匹配下面的网址:
/产品/嗒嗒
/产品/苹果
Copy after login

因为详细()动作期望的是一个整数值,发起一个含有非整数值的请求将会导致错误。举个例子,如果你在浏览器中输入/产品/苹果网址,那么你将会得到图1所示的错误页。

03 (1).jpg

图1:错误页

你实际想做的是只匹配包含合适整数productId参数的URL。当定义路由来限制与路由相匹配的网址时,你可以使用约束。代码3中的修改后的产品路由包含了一个正则表达式,它限制了只匹配数字。

代码清单3 - Global.asax.cs

routes.MapRoute(
    “Product”,
    “Product / {productId}”,
    new {controller =“Product”,action =“Details”},
    new {productId = @“\ d +”} 
 )
Copy after login

正则表达式\ D +匹配一个或多个整数这个限制使得产品路由匹配了下面的网址:

/产品/ 3
/产品/ 8999
但是不匹配下面的网址:
/产品/苹果
/产品
Copy after login

这些浏览器请求将自由另外的路由处理,或者,如果没有匹配的路由,将会返回一个“资源找不到”错误。

创建一个自定义路由约束

这篇教程的目标是演示如何创建一个自定义路由约束。自定义路由约束允许你阻止某个路径被匹配,除非满足一些自定义的条件。

在这篇教程中,我们创建了一个本地主机路由约束.Localhost路由约束只匹配本地计算机发出的请求。通过互联网发出的远程请求不会被匹配。

。你可以通过实现IRouteConstraint接口来实现一个自定义路由这是一个极其简单的接口,它只描述了一个方法:

bool Match(
    HttpContextBase httpContext,
    Route route,
    string parameterName,
    RouteValueDictionary值,
    RouteDirection routeDirection 
)
Copy after login

这个方法返回一个布尔值。如果返回了假,与约束相关联的路由将不会匹配浏览器请求。

本地主机约束包含在了代码清单1中。

代码清单1 - LocalhostConstraint.cs

使用 System.Web; 
使用 System.Web.Routing; 
命名空间 MvcApplication1.Constraints 
{ 
    public class LocalhostConstraint:IRouteConstraint 
    { 
        public bool Match 
            (
                HttpContextBase httpContext,
                Route route,
                string parameterName,
                RouteValueDictionary values,
                RouteDirection routeDirection 
            )
        { 
            return httpContext.Request.IsLocal; 
        } 
    } 
}
Copy after login

代码清单1中的约束利用了HttpRequest的类公布的IsLocal属性。当发出请求的IP地址是127.0.0.1或者与服务器的IP地址相同时,这个属性返回真。

你在定义于Global.asax中的路由中使用了自定义约束。代码清单2中的Global.asax中文件使用了本地主机约束来阻止任何人请求管理员页面,除非他们从本地服务器发出请求。举个例子,当请求来自远程服务器时,对于/管理/ DeleteAll的请求将会失败。

代码清单2 - Global.asax

使用系统; 
使用 System.Collections.Generic; 
使用 System.Linq; 
使用 System.Web; 
使用 System.Web.Mvc; 
使用 System.Web.Routing; 
使用 MvcApplication1.Constraints; 
命名空间 MvcApplication1
{
    public class MvcApplication:System.Web.HttpApplication
    {
         public static void RegisterRoutes(RouteCollection routes){
            routes.IgnoreRoute( “{resource} .axd / {* pathInfo}”); 
            routes.MapRoute(
                “Admin”,
                “Admin / {action}”,
                
                isLocal = new LocalhostConstraint()} 
            ); 
            //routes.MapRoute(
            //    “默认”,//路线名称
            //    “{控制器} / {行动} /(编号)”,// URL与参数
            //    新 {控制器= “主页”,动作=“索引“,id =”“ } //参数defaults 
            //); 
        } 
        protected void Application_Start(){ 
            RegisterRoutes(RouteTable.Routes); 
        } 
    } 
}
Copy after login

本地主机约束使用在了管理路由的定义中这个路由不会被远程浏览器请求所匹配然而,应该意识到定义在Global.asax中中的其他路由可能会匹配相同的请求理解这一点很重要。:约束阻止了特定路由匹配某一请求,而不是所有定义在Global.asax中文件中的路由。

注意到默认路由在代码清单2中的Glabal.asax文件中被注释掉了。如果你包含默认路由,那么默认路由将会匹配对管理控制器的请求。在这种情况下,远程用户仍然可以调用管理控制器的动作,即使他们的请求不匹配管理路由。

【相关推荐】

1. 什么是ASP.NET MVC ?总结ASP.NET MVC

2. 详细介绍ASP.NET MVC--控制器(controller)

3. 详细介绍ASP.NET MVC--视图

4. 深入了解ASP.NET MVC与WebForm的区别

5. 通过asp.net mvc开发微信自定义菜单编辑工具的代码示例

The above is the detailed content of Detailed introduction to ASP.NET MVC-routing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!