1.2.2.Route

1. Convention-based route

  • 客製化url: /Movies/released/2015/4

    • 1.在App_start/RouteConfig.cs中加入以下code, 他將會去呼叫MoviesController.cs中的ByReleaseDate

        routes.MapRoute(
            "MovieByReleaseDate",
            "movies/released/{year}/{month}",
            new { controller = "Movies", action = "ByReleaseDate" });
    • 2.在MoviesController.cs中加入以下code

      • mvcaction4 + tab 可快速產生 public ActionResult

        public ActionResult ByReleaseDate(int year, int month)
        {
          return Content(year + "/" + month);
        }

2. Attribute route

  • To avoid RouteConfig.cs and controller were not consistent

  • 1.修改route: RouteConfig.cs

              routes.MapMvcAttributeRoutes();
  • 2.修改controller: MoviesController.cs

    • Constraints

      • min

      • max

      • minlength

      • maxlength

      • int

      • float

      • guid

            [Route("movies/released/{year}/{month:regex(\\d{4}):range(1, 12)}")]
             public ActionResult ByReleaseDate(int year, int month)
             {
                return Content(year + "/" + month);
             }

Last updated