MVC-路由(Route)

  1. 启动路由准备工作

        public class MvcApplication : HttpApplication
        {
            protected void Application_Start()
            {
                //===============注册区域===============
                AreaRegistration.RegisterAllAreas();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                //===========注册路由======================还可以注册全局过滤器...
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
            }
        }
    Hide Code
  2. App_Start\RouteConfig.cs配置路由

    1. 传统路由的配置与使用

      public static void RegisterRoutes(RouteCollection routes)
              {
                  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
      
                  routes.MapRoute(
                      "Default",
                      "{controller}/{action}/{id}",
                      new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                  );
              }
      
      Hide Code
      Hide Code
    2. 属性路由路由的配置与使用

              public static void RegisterRoutes(RouteCollection routes)
              {
                  //启用属性路由//要放在上面!!!!!!!!!!!!有顺序要求的!!!
                  routes.MapMvcAttributeRoutes();
                  routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
      
                  routes.MapRoute(
                      "Default",
                      "{controller}/{action}/{id}",
                      new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                  );
              }
      Hide Code
  • 使用(在Controller中用):

      public class TestController : Controller
        {
            [HttpGet]
            [Route("~/Home/Get/{id}")]
            public JsonResult GetList(int id)
            {
                return Json(id, JsonRequestBehavior.AllowGet);
            }
        }
    Hide Code
  • 使用(在url或其他url应用):

    访问
    http://localhost:5000/Home/Get/10000
    即可进入TestController 对应的控制器
  • 输出内容

   

 

posted @ 2023-07-04 14:40  我是韩一  阅读(32)  评论(0编辑  收藏  举报