# Routing
1. There are 2 routing techniques in ASP.NET Core MVC. Conventional Routing and Attribute Routing.
2. Default Route in ASP.NET Core MVC, is defined using method
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
This is what configured using above method
{controller=Home}/{action=Index}/{id?}
3. http://localhost:1234/Employees/Details/1
In the above example
Path Segment Maps to
/Employees EmployeesController class
/Details Details(int id) action method
/1 id parameter of the Details(int id) action method
4. Attribute routing
app.UseMvc();
- With attribute routing, we use the Route attribute to define our routes. We could apply the Route attribute on the Controller or on the Controller Action Methods.
[Route("")]
[Route("Home")]
[Route("Home/Index")]
public ViewResult Index()
{
return View();
}
- With these 3 route templates in place, the Index() action method of the HomeController will be executed for any of the following 3 URL paths.
/
/Home
/Home/Index
5. To make the route parameter "id" optional, simply include a "?" at the end.
[Route("Home/Details/{id?}")]
// ? makes id method parameter nullable
public ViewResult Details(int? id)
6. Controller and Action Method Names
With attribute routing the controller name and action method names play no role in which action is selected. Consider the example below.
public class WelcomeController : Controller
{
[Route("")]
[Route("Home")]
[Route("Home/Index")]
public ViewResult Welcome()
{
return View();
}
}
Since we have specified the route template directly on the action method, Welcome() action in the WelcomeController is executed for all the following 3 URL paths.
/
/Home
/Home/Index
7. To make attribute routing less repetitive, route attributes on the controller are combined with route attributes on the individual action methods.
8. Tokens in Attribute Routing
Attribute routes support token replacement by enclosing a token in square-braces ([ ]). The tokens [controller] and [action] are replaced with the values of the controller name and action name where the route is defined.
Tuesday, 22 March 2022
Routing
Subscribe to:
Post Comments (Atom)
Search This Blog
Creating your first "Alexa" Skill
Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...
About Me
Menu
-
Index What is Alexa What is Alexa Skill? Why is it required when Alexa already equipped with voice assistant? Dev...
-
Adding Azure AD B2C to React Native App Register your app in Azure active directory 1. Go to azure ad b2c, app registratio...
-
# Project file 1. .net Core project file no longer contains file or folder reference - all files and folder present within the root fol...
No comments:
Post a Comment