From 7a9d3dc187ccbfe48904f7962f92b524e7c84685 Mon Sep 17 00:00:00 2001 From: "jason.zhu" Date: Wed, 16 Jun 2021 15:19:43 +1000 Subject: [PATCH] Finished 'Attribute Routing with Optional Parameter' --- 2_Routing.md | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/2_Routing.md b/2_Routing.md index 86dfa3d..9a4fd62 100644 --- a/2_Routing.md +++ b/2_Routing.md @@ -293,8 +293,31 @@ Now `http://localhost:xxxx/students/2/courses` will be routed to `GetStudentCour * controller action method have `[Route]` attribute use Attribute Routing * controller action method without `[Route]` attribute uses Convention-based routing. -## Attribute Routing in ASP.NET MVC - ## Attribute Routing with Optional Parameter +URI parameter can also be defined in attribute routing by adding **question mark ("?")** to router parameter within `{}`. We can also specify default value by **parameter = value** + +e.g. optional URI Parameter `{studentName? }` + +```csharp + // Optional URI Parameter + // URL: /MVCTest/ + // URL: /MVCTest/Pranaya + [Route("MVCTest/{studentName ?}")] + public ActionResult MVC(string studentName) + { + DoSth(studentName); + return View(); + } + // Optional URI Parameter with default value + // URL: /WEBAPITest/ + // URL: /WEBAPITest/Pranaya + [Route("WEBAPITest/{studentName = Pranaya}")] + public ActionResult WEBAPI(string studentName) + { + DoSth(studentName); + return View(); + } +``` + ## Route Prefix in Attribute Routing \ No newline at end of file