[英]custom Routing from controller level in MVC5?
我试图在MVC5中定义自定义路由,如下所示。 但是,当我打电话给http://company.com/protected/Myaccount
它不起作用。 我做错了。
以及如何通过http://company.com/protected
定义默认负载。 现在正在加载http://company.com/
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Protected",
url: "protected/{controller}/{action}/{id}",
defaults: new { controller = "MyAccount", action = "Index", id = UrlParameter.Optional });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "MyAccount", action = "Index", id = UrlParameter.Optional});
}
[RoutePrefix("Protected")]
[Route("{action=index}")]
public class MyAccountController : Controller
{
// GET: MyAccount
public ActionResult Index()
{
...
}
}
编辑:我忘了你的问题的第二部分。
[RoutePrefix("Protected")]
public class MyAccountController : Controller
{
[Route("Index")] //Route: /Protected/Index
[Route("")] //Route : /Protected
[Route("~/")] //Route : /
public ActionResult Index()
{
return View();
}
}
使用[RoutePrefix]可以更改对控制器的访问,使用[Route]可以更改对操作(例如:参数和顺序)的访问,并为控制器和应用程序定义默认值。
在这种情况下,我删除了RegisterRoute上的“ Protected”路由,因为未使用它。 RouteAttributes是另一种解决方案
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//routes.MapRoute(
// name: "Protected",
// url: "Protected/{Controller}/{action}/{id}",
// defaults: new { controller = "MyAccount", action = "Index", id = UrlParameter.Optional }
//);
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}/{id}",
// defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
//);
}
实际上,属性路由是定义路由的另一种方法,它更灵活。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.