什么是路由,对于初学者来说确实会有点搞不清楚!
官方解释,ASP.NET 路由模块负责将传入浏览器请求映射到特定的 MVC 控制器操作
目录
1、路由设置
ASP.NET MVC,最大的一个特点就是引入了路由的概念。
以下是.net framework框架的路由设置
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Test.Controllers" }
);
}
}
2、请求地址
假设请求地址为:/Area/Test/List/123
3、错误写法
不能直接使用TestID来接受参数
public async Task<ActionResult> TestItem(int TestID)
{
return View();
}
4、正确写法
public async Task<ActionResult> TestItem(int id)
{
int TestID = id;
return View();
}
5、官方默认写法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit https://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
6、 使用自定义路由
添加到路由表的路由的顺序非常重要。 新的自定义博客路由在现有默认路由之前添加。 如果撤消了顺序,则默认路由将始终被调用,而不是自定义路由。
自定义博客路由与以 /Archive/开头的任何请求匹配。 因此,它匹配以下所有 URL:
-
/Archive/12-25-2009
-
/Archive/10-6-2004
-
/Archive/apple
自定义路由将传入请求映射到名为 Archive 的控制器,并调用 Entry () 操作。 调用 Entry () 方法时,条目日期将作为名为 entryDate 的参数传递。