ASP.NET MVC 5新特性:Attributeルーティング使用詳細

10058 ワード

1、   Attribute  ?     Attribute  ?

      ASP.NET MVC5           :Attribute  ,    ,Attribute     Attribute     。  ,MVC5            ,                       。

               RouteConfig.cs               :

routes.MapRoute(

name: "ProductPage",

url: "{productId}/{productTitle}",

defaults: new { controller = "Products", action = "Show" },

constraints: new { productId = "\\d+" }

);

   MVC5 ,           Action     :

[Route("{productId:int}/{productTitle}")]

public ActionResult Show(int productId) { ... }

    ,     Attribute  ,      MapMvcAttributeRoutes     Attribute  :

public class RouteConfig

{

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapMvcAttributeRoutes();

}

}


2、URL        

          “?”         ,           :

public class BooksController : Controller

{

//   : /books

//   : /books/1430210079

//      isbn     

[Route("books/{isbn?}")]

public ActionResult View(string isbn)

{

if (!String.IsNullOrEmpty(isbn))

{

return View("OneBook", GetBook(isbn));

}

return View("AllBooks", GetBooks());

}

//   : /books/lang

//   : /books/lang/en

//   : /books/lang/he

//   URL    lang   , lang   “en”

[Route("books/lang/{lang=en}")]

public ActionResult ViewByLanguage(string lang)

{

return View("OneBook", GetBooksByLanguage(lang));

}

}


3、    

          Controller  ,   Action     URL         ,  :

public class ReviewsController : Controller

{

//   : /reviews

[Route("reviews")]

public ActionResult Index() { ... }

//   : /reviews/5

[Route("reviews/{reviewId}")]

public ActionResult Show(int reviewId) { ... }

//   : /reviews/5/edit

[Route("reviews/{reviewId}/edit")]

public ActionResult Edit(int reviewId) { ... }

}

       ReviewsController      Action       "reviews",        Controller     [RoutePrefix]      ,    Action      URL         "reviews":

[RoutePrefix("reviews")]

public class ReviewsController : Controller

{

//   : /reviews

[Route]

public ActionResult Index() { ... }

//   : /reviews/5

[Route("{reviewId}")]

public ActionResult Show(int reviewId) { ... }

//   : /reviews/5/edit

[Route("{reviewId}/edit")]

public ActionResult Edit(int reviewId) { ... }

}

    ,      Action           ?     ,        “~”    :

[RoutePrefix("reviews")]

public class ReviewsController : Controller

{

//   : /spotlight-review

[Route("~/spotlight-review")]

public ActionResult ShowSpotlight() { ... }

...

}


4、    

          Action    [Route] ,      Controller  , [Route]   Controller   ,             ,      Controller      Action    ,     Action       [Route]       Controller   [Route]。          Controller    [Route]       {action},     “RouteData       'action'          。”  。    Action    [Route]     ,   {action}      Action。

[RoutePrefix("promotions")]

[Route("{action=index}")]

//         ,  {action}     "index",

//     URL     {action}  ,      Action   Index。

public class ReviewsController : Controller

{

//   : /promotions

public ActionResult Index() { ... }

//   : /promotions/archive

public ActionResult Archive() { ... }

//   : /promotions/new

public ActionResult New() { ... }

//   : /promotions/edit/5

//            

//       ,      :/promotions/editProduct?promoId=5

[Route("edit/{promoId:int}")]

public ActionResult EditProduct(int promoId) { ... }

}


5、    

                      ,   :{  :  },    :

//   : /users/5

[Route("users/{id:int}"]

//        “id”       

public ActionResult GetUserById(int id) { ... }


              :

alpha,        (a-z,A-Z), :{x:alpha};

bool,      , :{x:bool}

datetime,   DateTime(     )  , :{x:datetime}

decimal,   decimal  , :{x:decimal}

double,   64bit   , :{x:double}

float,   32bit   , :{x:float}

guid,   GUID, :{x:guid}

int,   32bit  , :{x:int}

length,                   , :{x:length(6)} {x:length(1,20)}

long,   64bit  , :{x:long}

max,          , :{x:max(10)}

maxlength,            , :{x:maxlength(10)}

min,            , :{x:min(10)}

minlength,            , :{x:minlength(10)}

range,           , :{x:range(10,50)}

regex,          , :{x:(^\d{3}-\d{3}-\d{4}$)}


                  ,       ,  :

//   : /users/5

//       /users/10000000000   id       int.MaxValue,

//      /users/0       min(1)  ,id          1.

[Route("users/{id:int:min(1)}")]

public ActionResult GetUserById(int id) { ... }


                  ,  :

//   : /greetings/bye

//     /greetings   message     ,

//       /greetings/see-you-tomorrow    maxlength(3)  .

[Route("greetings/{message:maxlength(3)?}")]

public ActionResult Greet(string message) { ... }


6、       

           IRouteConstraint           。                :

public class ValuesConstraint : IRouteConstraint

{

private readonly string[] validOptions;

public ValuesConstraint(string options)

{

validOptions = options.Split('|');

}

public bool Match(HttpContextBase httpContext, Route route,

string parameterName, RouteValueDictionary values,

RouteDirection routeDirection)

{

object value;

if (values.TryGetValue(parameterName, out value) && value != null)

{

return validOptions.Contains(value.ToString(), StringComparer.OrdinalIgnoreCase);

}

return false;

}

}

                    

public class RouteConfig

{

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

var constraintsResolver = new DefaultInlineConstraintResolver();

constraintsResolver.ConstraintMap.Add("values", typeof(ValuesConstraint));

routes.MapMvcAttributeRoutes(constraintsResolver);

}

}

                        :

public class TemperatureController : Controller

{

//    temp/celsius    /temp/fahrenheit      /temp/kelvin

[Route("temp/{scale:values(celsius|fahrenheit)}")]

public ActionResult Show(string scale)

{

return Content("scale is " + scale);

}

}


7、    

                ,        URL,    :

[Route("menu", Name = "mainmenu")]

public ActionResult MainMenu() { ... }

        Url.RouteUrl        URL:

<a href="@Url.RouteUrl("mainmenu")">Main menu</a>


8、Area

  ASP.NET MVC   Area        Web        , Attribute             ,     [RouteArea],     Controller        Area  ,           Area    AreaRegistration   :


[RouteArea("Admin")]

[RoutePrefix("menu")]

[Route("{action}")]

public class MenuController : Controller

{

//   : /admin/menu/login

public ActionResult Login() { ... }

//   : /admin/menu/show-options

[Route("show-options")]

public ActionResult Options() { ... }

//   : /stats

[Route("~/stats")]

public ActionResult Stats() { ... }

}


                  "Admin" Area,         URL "/Admin/menu/show-options":

Url.Action("Options", "Menu", new { Area = "Admin" })

         AreaPrefix     Area   ,  :

[RouteArea("BackOffice", AreaPrefix = "back-office")]


          Attribute、AreaRegistration           Area   ,       Attribute               AreaRegistration    Area,     ,                             ,           ,              ,          ,               。           :


public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapMvcAttributeRoutes();

AreaRegistration.RegisterAllAreas();

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

);

}