MVC 自定义路由

RouteConfig.cs 代码如下:

 public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //自定义路由标签
            routes.MapMvcAttributeRoutes();
           
            //默认路由
            //routes.MapRoute(
            //    name: "Default",
            //    url: "{controller}/{action}/{id}",
            //    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            //    namespaces: new string[] { "WebTest.Controllers" }
            //);
        }
    }

Controller自定义路由标签:

 [RoutePrefix("Test")]
    public class ProductController : Controller
    {
        
        [HttpGet,Route("Index")]
        public ActionResult Index(int? pageIndex=1,int? pageSize=8)
        {
            ProductService service = new ProductService();
            int index = Convert.ToInt32(pageIndex);
            int size = Convert.ToInt32(pageSize);
            var list = service.GetList(index, size);
            ViewBag.products = list;
            return View();
        }

        [HttpGet,Route("Demo")]
        public ActionResult One()
        {
            List<UserModel> list = new List<UserModel>();
            for (int i = 1; i < 10; i++)
            {
                list.Add(new UserModel()
                {
                    Id = i,
                    Name = "test"+i,
                    Password = "123456"
                });
            }
            ViewBag.Users = list;
            return View();
        }
    }
原文地址:https://www.cnblogs.com/zoro-zero/p/6025524.html