Detailed introduction of ASP. NET Core 2.0 Route engine URL generation, asp. netcore

Source: Internet
Author: User
Tags web hosting

Detailed introduction of ASP. NET Core 2.0 Route engine URL generation, asp. netcore

Problem

In ASP. NET Core 2.0, how does one generate a URL by the routing engine?

Answer

Create an empty project, modify the Startup. cs file, and add the 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)"); }} 

Discussion

We can use the MVC web hosting mechanism to generate a website without the need to hardcode the website in the application. MVC has all the information for doing so, from the template we provide for setting the route ing.

MVC provides the IUrlHelper interface to generate a URL. This is achieved by publishing Url attributes in the controller base class, view, and attempt component.

The IUrlHelper interface provides two key methods to generate a URL:

1. Action: The URL is generated by providing the controller, method, and route parameter value.
2. RouteUrl: the URL is generated by providing the route ing name and route parameters.

If the Controller and route parameters are not provided when the preceding method is called, MVC will obtain the parameters from the current request or method parameters (that is, from the environment variables of the current context ). The following method exists 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 concatenated as URL query strings:

public IActionResult PageFour(){ var url = Url.RouteUrl("goto_two", new { id=5, key1 = "value1" }); // /two/5?key1=value1 return Content($"Mobile/Four (Url: {url})");} 

The ControlBase class has a convenient method, RedirectToAction, which is used to redirect user requests to a controller method. This process is completed on the client:

public IActionResult PageFive(){ return RedirectToAction("PageSix");} public IActionResult PageSix(){ return Content("Mobile/Six (Mobile/Five will also come here)");} 

  
  

To inject IUrlHeper into the required class as a dependency, we need to configure the corresponding service 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 Url attributes are already published in the Controller and view for our use.

Source code download

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

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.