ASP.NET MVC 中动态从路由中获取URL

在mvc中我们需要经常动态从路由中获取url的地址,下面我们就来学习下这个过程。(本人由于初学这个东东,难免有差错,请大家踊跃指出我会加以改正!!谢谢大家)

直接看代码:HomeController的代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 using System.Web.Routing;
 7 
 8 namespace 有路由动态获取url的值.Controllers
 9 {
10     public class HomeController : Controller
11     {
12         //
13         // GET: /Home/
14 
15         public ActionResult Index()
16         {
17             //获取路由列表里面的指定路由(Default)的路由对象
18             VirtualPathData vp = RouteTable.Routes.GetVirtualPath(null, "Default", new RouteValueDictionary(new { controller = "Home", action = "Index", id = 1 }));
19             //当我们设置的路由字典new { controller = "Home", action = "Index", id = 1 }
20             //和Global.asax.cs中的值一样的时候.我们只能获取“/”也就是虚拟根路径
21             //VirtualPathData vp = RouteTable.Routes.GetVirtualPath(null, "Default", new RouteValueDictionary(new { controller = "Home", action = "Index", id = 1 }));
22             //获取路由属性值----url
23             string url = vp.VirtualPath;
24             ViewData["message"] = url;
25             return View();
26         }
27 
28     }
29 }

首先我们先看下HomeController中的代码,我们使用GetVirtualPath()方法来获取路由列表中指定的路由“Default”中对象。此方法有2个重载,区别在于“string name”。有name的获取“指定的路由对象”,没有“name”的是获取默认的路由对象。

其次vp.VirtualPath属性获取指定路由对象的url并保存在变量url中,然后在输出。

最后我们要注意的是:当我们设置的路由字典new { controller = "Home", action = "Index", id = 1 }和Global.asax.cs中的值一样的时候.我们只能获取“/”也就是虚拟根路径。

附上:Global.asax

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 using System.Web.Routing;
 7 
 8 namespace 有路由动态获取url的值
 9 {
10     // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
11     // 请访问 http://go.microsoft.com/?LinkId=9394801
12 
13     public class MvcApplication : System.Web.HttpApplication
14     {
15         public static void RegisterRoutes(RouteCollection routes)
16         {
17             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
18 
19             routes.MapRoute(
20                 "Default", // 路由名称
21                 "{controller}/{action}/{id}", // 带有参数的 URL
22                 new { controller = "Home", action = "Index", id = 0 } // 参数默认值
23             );
24 
25         }
26 
27         protected void Application_Start()
28         {
29             AreaRegistration.RegisterAllAreas();
30 
31             RegisterRoutes(RouteTable.Routes);
32         }
33     }
34 }

再附上:view中 Index.aspx的代码

 1 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml" >
 6 <head runat="server">
 7     <title>Index</title>
 8 </head>
 9 <body>
10     <div>
11     <%=ViewData["message"] %>
12     </div>
13 </body>
14 </html>