Detailed explanation ASP.NET Web address generation of core 2.0 routing engine

Time:2020-11-14

problem

How to ASP.NET In core 2.0, the routing engine generates the web address?

answer

Create an empty item, modify Startup.cs File, add MVC service and middleware:


public void ConfigureServices(IServiceCollection services)

{

 services.AddMvc();

}

 

public void Configure(IApplicationBuilder app, IHostingEnvironment env)

{

 if (env.IsDevelopment())

 {

  app.UseDeveloperExceptionPage();

 }

 

 app.UseMvc(routes =>

 {

  routes.MapRoute(

   name: "goto_one",

   template: "one",

   defaults: new { controller = "Home", action = "PageOne" });

 

  routes.MapRoute(

   name: "goto_two",

   template: "two/{id?}",

   defaults: new { controller = "Home", action = "PageTwo" });

 

  routes.MapRoute(

   name: "default",

   template: "{controller=Home}/{action=Index}/{id?}");

 });

} 

Add a mobilecontroller controller class:


 public class MobileController : Controller

{

 public IActionResult Index()

 {

  var url = Url.Action("Index"); // /mobile

  return Content($"Mobile/Index (Url: {url})");

 }

 

 public IActionResult PageOne()

 {

  var url = Url.Action("PageOne"); // /mobile/PageOne

  return Content($"Mobile/One (Url: {url})");

 }

 

 [HttpGet]

 public IActionResult PageTwo()

 {

  var url = Url.Action("PageTwo"); // /mobile/PageTwo OR /mobile/PageTwo/1?

  return Content($"(GET) Mobile/Two (Url: {url})");

 }

 

 [HttpPost]

 public IActionResult PageTwo(int id)

 {

  var url = Url.Action("PageTwo"); // /mobile/PageTwo/1

  return Content($"(POST) Mobile/Two: {id} (Url: {url})");

 }

 

 public IActionResult PageThree()

 {

  var url = Url.RouteUrl("goto_two", new { id = 5 }); // /two/5

  return Content($"Mobile/Three (Url: {url})");

 }

 

 public IActionResult PageFour()

 {

  var url = Url.RouteUrl("goto_two", new { q = 5 }); // /two?q=5

  return Content($"Mobile/Four (Url: {url})");

 }

 

 public IActionResult PageFive()

 {

  return RedirectToAction("PageSix");

 }

 

 public IActionResult PageSix()

 {

  return Content("Mobile/Six (Mobile/Five will also come here)");

 }

} 

discuss

We can use MVC’s routing mechanism to generate web addresses without hard coding them in the application. MVC has all the information to do this, from the template we provided to set up the routing map.

MVC provides iurlhelper interface to provide the function of generating web address. This is achieved by exposing the URL property in the controller base class, view and attempt components.

Iurlhelper interface provides two key methods to generate web address:

1. Action: generate web address by providing controller, method and route parameter values.
2. Routeurl: generate web address by providing route mapping name and route parameters.

If the controller and routing parameters are not provided when calling the above method, MVC will get it from the current request or method parameters (that is, from the environment variables of the current context). The following methods exist in the mobilecontroller controller:


public IActionResult PageTwo(int id)

{

 var url = Url.Action("PageTwo"); // /mobile/PageTwo/1

 return Content($"(POST) Mobile/Two: {id} (Url: {url})");

}

Routing parameters can be provided as anonymous objects:


 public IActionResult PageThree()

{

 var url = Url.RouteUrl("goto_two", new { id = 5 }); // /two/5

 return Content($"Mobile/Three (Url: {url})");

} 

If MVC cannot map these values to address tags, these parameters are spliced together as query strings for web addresses:


public IActionResult PageFour()

{

 var url = Url.RouteUrl("goto_two", new { id=5, key1 = "value1" }); // /two/5?key1=value1

 return Content($"Mobile/Four (Url: {url})");

} 

There is a convenient method called redirecttoaction on the controlbase class, which is used to redirect user requests to a controller method. This process is completed on the client side


public IActionResult PageFive()

{

 return RedirectToAction("PageSix");

}

 

public IActionResult PageSix()

{

 return Content("Mobile/Six (Mobile/Five will also come here)");

} 

  
  

In order to inject iurlheper as a dependency into the required classes, we need to first configure the corresponding services in configureservices


public void ConfigureServices(IServiceCollection services)

{

 services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

 services.AddScoped<IUrlHelper>(factory =>

 {

  var actionContext = factory.GetService<IActionContextAccessor>().ActionContext;

  return new UrlHelper(actionContext);

 });

 

 services.AddMvc();

}   

Note: in most cases, we do not need to use iurlhelper through injection, because the URL attribute has been exposed in the controller and view for us to use.

Source code download

Original text: https://tahirnaushad.com/2017/08/20/asp-net-core-mvc-routing/

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.