欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Route

程序员文章站 2022-06-02 18:35:20
...
  1. General
routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}");

匹配:

http://mydomain.com/Admin/Index
http://mydomain.com/Home/Index    (默认)
  1. Static URL Segments
routes.MapRoute(name: "", template: "Public/{controller=Home}/{action=Index}");

匹配:

http://mydomain.com/Public/Admin/Index
http://mydomain.com/Public/Home/Index    (默认)
  1. Mixed
routes.MapRoute("", "X{controller}/{action}");

匹配:

http://mydomain.com/XAdmin/Index
http://mydomain.com/XHome/Index

应用:

routes.MapRoute("", "Shop/OldAction", new { controller = "Home", action = "Index" });

会匹配到

http://mydomain.com/Home/Index
  1. 自定义Segment变量
routes.MapRoute("", "{controller=Home}/{action=Index}/{id=DefaultId}");

Note: controller,action和area为保留字

  1. 可选Segment
routes.MapRoute("", "{controller=Home}/{action=Index}/{id?}");
  1. catchall
routes.MapRoute("", "{controller=Home}/{action=Index}/{id?}/{*catchall}");

匹配:

http://mydomain.com/Home/List/123/123/12/31/2312/3

其中catchall为"123/12/31/2312/3"

  1. 约束Routes
routes.MapRoute("", "{controller=Home}/{action=Index}/{id:int?}");

匹配:

http://mydomain.com/CustomVariable/Hello/1
  1. Attribute Routing
  public class CustomerController : Controller
    {
        [Route("myroute")]
        public ViewResult Index() => View("Result", new Result { Controller = nameof(CustomerController), Action = nameof(Index) });
        public ViewResult List() => View("Result", new Result { Controller = nameof(CustomerController), Action = nameof(Index) });
    }

匹配:

http://mydomain.com/myroute

且无法通过如下Url访问:

http://mydomain.com/Customer/Index

可以添加[controller]:

    public class CustomerController : Controller
    {
        [Route("[controller]/MyAction")]
        public ViewResult Index() => View("Result", new Result { Controller = nameof(CustomerController), Action = nameof(Index) });
        public ViewResult List() => View("Result", new Result { Controller = nameof(CustomerController), Action = nameof(Index) });
    }

匹配:

http://mydomain.com/Customer/MyAction