在ASP.NET MVC中,路由是将传入请求映射到正确控制器和操作的机制。可以使用自定义路由来更改默认的路由行为。其中一种常见情况是为具有多个区域的应用程序添加基于区域的自定义路由。下面是一个示例:
在Global.asax.cs文件中,注册区域路由:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
在区域中创建一个名为Home的控制器:
// ~/Areas/MyArea/Controllers/HomeController.cs
namespace MyArea.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return Content("This is home page of MyArea");
}
}
}
然后在区域的AreaRegistration.cs文件中,定义区域的路由:
// ~/Areas/MyArea/MyAreaRegistration.cs
namespace MyArea
{
public class MyAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "MyArea";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"MyArea_default",
"MyArea/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
在这里,我们使用MapRoute方法自定义MyArea区域的路由。当控制器为Home时,可以在浏览器中调用http://localhost:xxx/MyArea来访问它。