public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Here I have created a custom "Default" route that will route users to the "YourAction" method within the "FooController" controller.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "FooController", action = "Index", id = UrlParameter.Optional }
);
}
3
步骤1:单击解决方案中的Global.asax文件 .
第2步:然后转到定义
RouteConfig.RegisterRoutes(RouteTable.Routes);
第3步:更改控制器名称和视图名称
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 }
);
}
}
public class HomeController : Controller
{
// url is now 'index/' instead of 'home/index'
[Route("index")]
public ActionResult Index()
{
return View();
}
// url is now 'create/new' instead of 'home/create'
[Route("create/new")]
public ActionResult Create()
{
return View();
}
}
1
我尝试了答案,但它对我不起作用 . 这就是我最终做的事情:
创建一个新的控制器DefaultController . 在索引操作中,我写了一行重定向:
return Redirect("~/Default.aspx")
在RouteConfig.cs中,更改路径的controller =“Default” .
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
7 回答
检查global.asax.cs中的RegisterRoutes方法 - 它是路由配置的默认位置...
查看
Default.aspx/Default.aspx.cs
和Global.asax.cs您可以设置默认路由:
只需将控制器/操作名称更改为所需的默认值即可 . 这应该是路由表中的最后一条路由 .
ASP.NET核心
路由在
Startup
类的Configure
方法中配置 . 要设置"homepage",只需添加以下内容即可 . 当用户导航到您网站的基本网址时,这将导致用户被路由到MapRoute方法中定义的控制器和操作,即,yoursite.com会将用户路由到yoursite.com/foo/index:Pre-ASP.NET核心
使用位于App_Start / RouteConfig.cs(MVC 3和4)或Global.asax.cs(MVC 1和2)中的RegisterRoutes方法,如下所示 . 这将导致用户路由到MapRoute方法中定义的控制器和操作,如果他们导航到您站点的基本URL,即yoursite.com将用户路由到yoursite.com/foo/index:
步骤1:单击解决方案中的Global.asax文件 .
第2步:然后转到定义
RouteConfig.RegisterRoutes(RouteTable.Routes);
第3步:更改控制器名称和视图名称
MVC 5中的属性路由
在MVC 5之前,您可以通过在RouteConfig.cs文件中调用
routes.MapRoute(...)
将URL映射到特定的操作和控制器 . 这是存储主页的URL的位置(Home/Index
) . 但是,如果您修改默认路由,如下所示,请记住,这会影响其他操作和控制器的URL . 例如,如果您有一个名为
ExampleController
的控制器类及其内部的一个名为DoSomething
的操作方法,则预期的默认URLExampleController/DoSomething
将不再起作用,因为默认路由已更改 .解决此问题的方法是不要弄乱默认路由并在RouteConfig.cs文件中为其他操作和控制器创建新路由,如此,
现在
ExampleController
类的DoSomething
动作将映射到urlhey/now
. 但是,每次要为不同的操作定义路由时,这都会变得乏味 . 所以在MVC 5中你现在可以添加属性来匹配url到这样的动作,我尝试了答案,但它对我不起作用 . 这就是我最终做的事情:
创建一个新的控制器DefaultController . 在索引操作中,我写了一行重定向:
在RouteConfig.cs中,更改路径的controller =“Default” .