This article explains how to use ASP.NET Core routing to map actions to corresponding URLs in incoming requests.
Routes specify how actions and URL paths should correspond. It was used to produce URLs that were sent out in replies.
Make a ProductController first, and then, as indicated below, make a Details action.
[HttpGet] public IActionResult Details(int id) { return View(); }
To create the Details view, right-click on the Details action.
Start by opening your Startup class, and then add the default routing configuration as indicated below.
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); });
You should observe that the action receives the parameter from the routing if everything goes according to plan.
Proceed similarly and make a new Edit action.
[HttpGet] public IActionResult Edit(int productId) { return View(); }
Route attribute asp.net core
You can change your code as demonstrated below by using the route attribute in ASP.NET Core.
[HttpGet("{productId}")] public IActionResult Edit(int productId) { return View(); }
[Route("Product/Edit/{productId:int}")] public IActionResult Edit(int productId) { return View(); }
You can see your parameter from url passed to your action.
Creating a SearchByProduct api as shown below.
[Route("Product/Search/{category}/{keyword}")] public string[] SearchByProducts(string category, string keyword) { return new[] { $"{category}, {keyword}" }; }
You can also modify your routing as RESTful Routes.
api/product/search/furniture/camera
[Route("api/[controller]")] public class ProductController : Controller { //... }
[Route("Search/{category}/{keyword}")] public string[] SearchByProducts(string category, string keyword) { return new[] { $"{category}, {keyword}" }; }
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute( name: "api", pattern: "api/{controller}/{action}/{id?}"); endpoints.MapRazorPages(); });