Attribute Routing در ASP.NET MVC 5
نویسنده: آرمین ضیاء
تاریخ: ۱۳۹۲/۱۰/۲۵ ۲:۴۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
routes.MapRoute(
name: "ProductPage",
url: "{productId}/{productTitle}",
defaults: new { controller = "Products", action = "Show" },
constraints: new { productId = "\\d+" }
); [Route("{productId:int}/{productTitle}")]
public ActionResult Show(int productId) { ... } public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
} 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 }
);
} public class BooksController : Controller
{
// eg: /books
// eg: /books/1430210079
[Route("books/{isbn?}")]
public ActionResult View(string isbn)
{
if (!String.IsNullOrEmpty(isbn))
{
return View("OneBook", GetBook(isbn));
}
return View("AllBooks", GetBooks());
}
// eg: /books/lang
// eg: /books/lang/en
// eg: /books/lang/he
[Route("books/lang/{lang=en}")]
public ActionResult ViewByLanguage(string lang)
{
return View("OneBook", GetBooksByLanguage(lang));
}
} public class ReviewsController : Controller
{
// eg: /reviews
[Route("reviews")]
public ActionResult Index() { ... }
// eg: /reviews/5
[Route("reviews/{reviewId}")]
public ActionResult Show(int reviewId) { ... }
// eg: /reviews/5/edit
[Route("reviews/{reviewId}/edit")]
public ActionResult Edit(int reviewId) { ... }
} [RoutePrefix("reviews")]
public class ReviewsController : Controller
{
// eg.: /reviews
[Route]
public ActionResult Index() { ... }
// eg.: /reviews/5
[Route("{reviewId}")]
public ActionResult Show(int reviewId) { ... }
// eg.: /reviews/5/edit
[Route("{reviewId}/edit")]
public ActionResult Edit(int reviewId) { ... }
} [RoutePrefix("reviews")]
public class ReviewsController : Controller
{
// eg.: /spotlight-review
[Route("~/spotlight-review")]
public ActionResult ShowSpotlight() { ... }
...
} [RoutePrefix("promotions")]
[Route("{action=index}")]
public class ReviewsController : Controller
{
// eg.: /promotions
public ActionResult Index() { ... }
// eg.: /promotions/archive
public ActionResult Archive() { ... }
// eg.: /promotions/new
public ActionResult New() { ... }
// eg.: /promotions/edit/5
[Route("edit/{promoId:int}")]
public ActionResult Edit(int promoId) { ... }
} // eg: /users/5
[Route("users/{id:int}"]
public ActionResult GetUserById(int id) { ... }
// eg: users/ken
[Route("users/{name}"]
public ActionResult GetUserByName(string name) { ... } | مثال | توضیحات | محدودیت |
| {x:alpha} | کاراکترهای الفبای لاتین را تطبیق (match) میدهد (a-z, A-Z). | alpha |
| {x:bool} | یک مقدار منطقی را تطبیق میدهد. | bool |
| {x:datetime} | یک مقدار DateTime را تطبیق میدهد. | datetime |
| {x:decimal} | یک مقدار پولی را تطبیق میدهد. | decimal |
| {x:double} | یک مقدار اعشاری 64 بیتی را تطبیق میدهد. | double |
| {x:float} | یک مقدار اعشاری 32 بیتی را تطبیق میدهد. | float |
| {x:guid} | یک مقدار GUID را تطبیق میدهد. | guid |
| {x:int} | یک مقدار 32 بیتی integer را تطبیق میدهد. | int |
| {(x:length(6} {(x:length(1,20} | رشته ای با طول تعیین شده را تطبیق میدهد. | length |
| {x:long} | یک مقدار 64 بیتی integer را تطبیق میدهد. | long |
| {(x:max(10} | یک مقدار integer با حداکثر مجاز را تطبیق میدهد. | max |
| {(x:maxlength(10} | رشته ای با حداکثر طول تعیین شده را تطبیق میدهد. | maxlength |
| {(x:min(10} | مقداری integer با حداقل مقدار تعیین شده را تطبیق میدهد. | min |
| {(x:minlength(10} | رشته ای با حداقل طول تعیین شده را تطبیق میدهد. | minlength |
| {(x:range(10,50} | مقداری integer در بازه تعریف شده را تطبیق میدهد. | range |
| {(${x:regex(^\d{3}-\d{3}-\d{4} | یک عبارت با قاعده را تطبیق میدهد. | regex |
// eg: /users/5
// but not /users/10000000000 because it is larger than int.MaxValue,
// and not /users/0 because of the min(1) constraint.
[Route("users/{id:int:min(1)}")]
public ActionResult GetUserById(int id) { ... } // eg: /greetings/bye
// and /greetings because of the Optional modifier,
// but not /greetings/see-you-tomorrow because of the maxlength(3) constraint.
[Route("greetings/{message:maxlength(3)?}")]
public ActionResult Greet(string message) { ... } 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
{
// eg: temp/celsius and /temp/fahrenheit but not /temp/kelvin
[Route("temp/{scale:values(celsius|fahrenheit)}")]
public ActionResult Show(string scale)
{
return Content("scale is " + scale);
}
} [Route("menu", Name = "mainmenu")]
public ActionResult MainMenu() { ... } <a href="@Url.RouteUrl("mainmenu")">Main menu</a> [RouteArea("Admin")]
[RoutePrefix("menu")]
[Route("{action}")]
public class MenuController : Controller
{
// eg: /admin/menu/login
public ActionResult Login() { ... }
// eg: /admin/menu/show-options
[Route("show-options")]
public ActionResult Options() { ... }
// eg: /stats
[Route("~/stats")]
public ActionResult Stats() { ... }
} Url.Action("Options", "Menu", new { Area = "Admin" }) [RouteArea("BackOffice", AreaPrefix = "back-office")] 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 }
);
} 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 = "List", id = UrlParameter.Optional }
);
} [Route("Page/{page?}")]
public ActionResult List(int page=1)
{ [Route("~/")] [Route("~/Page/{page?}")]
public ActionResult List(int page=1)
{ [Route("~/")]
[Route("Page/{page?}")]
public ActionResult List(int page=1)
{ [RouteArea("Admin")]
[RoutePrefix("menu")]
[Route("{action}")]
public class MenuController : Controller
{
// eg: /admin/menu/login
public ActionResult Login() { ... }
// eg: /admin/menu/show-options
[Route("show-options")]
public ActionResult Options() { ... }
// eg: /stats
[Route("~/stats")]
public ActionResult Stats() { ... }