Detailed description of the ASP. NET Core Razor page Routing

Source: Internet
Author: User
This article mainly introduces the ASP. NET Core Razor page routing details, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

In the framework of server-side WEB applications, it is very important that developers match URLs to resources on the server for proper processing of requests. The simplest method is to map the URL to a physical file on disk, in the Razor page frame, in ASP. NET team to achieve this.

about how the Razor page framework matches URLs to files, there are rules that you must understand and how you can change the results of the output as you need to customize the rules. If you compare the Razor page with the Web Form framework, you also need to understand the superseded Ur l parameters and the mechanism to pass the data in the URL.

Rule one, the Razor page requires a root directory. By default, the root directory is Pages, which is located in the root directory of the Web application project. You can Startup ConfigureServices configure other folders as the root directory in the methods of the class. Here's how to change the root directory to be in the application "Content" folder:


public void Configureservices (iservicecollection services) {   Services    . Addmvc ().    Addrazorpagesoptions (options =     options. RootDirectory = "/content";   } );  }

Rule two, the URL maps to the Razor page, and the URL does not contain the file name extension.

Rule three, "index.cshtml" is a default document, which means that if

URL Mapping Files
www.domain.com /pages/index.cshtml
Www.domain.com/index /pages/index.cshtml
Www.domain.com/index /pages/index.cshtml
Www.domain.com/account /pages/account.cshtml or/pages/account/index.cshtml

In the last example, the URL maps to two different files-"index.cshtml" in the "account.cshtml", "Account" folder in the root directory. The Razor page framework does not recognize which file to select, so if you actually own the two files in your application, you will throw the following exception if you try to browse Www.domain.com/account:

Ambiguousactionexception:multiple actions matched. The following actions matched route data and had all constraints satisfied:

Page:/account/index

Page:/account

URL Pass Parameters

As with most other frameworks, parameters can be passed as query strings in URLs, such as: www.domain.com/product?id=1 or, you can pass them as route parameters, so the above example becomes www.domain.com/product/1 . Part of the URL must be mapped to the parameter name in the page's routing template to implement the ,@page instruction part:


@page "{ID}"

The template tells the framework to take the first paragraph of the URL after the page name as the "id" route parameter. You can access the values of the route parameters in several ways. The first is to use a RouteData dictionary:


@page "{id}" {var productId = routedata.values["id"];}

Alternatively, you can add a parameter to the page's OnGet() method with the same name as the route parameter and assign its value to a public property:


@page "{ID}" @{@functions {public  int id {get; set;}  public void onget (int id)  {   id = ID;}}  } <p>the Id is @Id </p>

If you are using PageModel , then this is achieved:


Using Microsoft.aspnetcore.mvc.razorpages;namespace razorpages.pages{public class Productmodel:pagemodel {  public int Id {get; set;}  public void onget (int id)  {   id = ID;}}  }


@page "{ID}" @model productmodel<p>the ID is @Model .id</p>

Finally, you can use attributes in the public attribute BindProperty , and omit the OnGet parameters in the method. The contents of the Razor file remain the same, but the PageModel code changes slightly:


Using Microsoft.aspnetcore.mvc.razorpages;namespace razorpages.pages{public class Productmodel:pagemodel {  [ BindProperty (Supportsget = true)] public  int Id {get; set;}  public void Onget ()  {  }}}

Constraints

Also, the constraint of the parameter in this example is that it must have a value. URL www.domain.com/product/appleas www.domain.com/product/21 valid, it is possible to match the route. If you want the id value to be an integer, you can specify the constraint by adding the data type to the template:


@page "{Id:int}"

Now, if you try to use "apple" as the parameter value, the application returns a 404 Not Found status code.

You can specify that the value is not required, and you can set the parameter to be a nullable type:


@page "{Id:int}"

If your application allows you to use "apple" as a parameter value, you can specify that only a-Z and a-Z characters are allowed:


@page "{Id:alpha}"

You can combine with minimum length requirements:


@page "{id:alpha:minlength (4)}"

For more information on constraints, you can view Microsoft Docs.

Friendly URLs

A friendly URL can map URLs to arbitrary files on disk, breaking a one-to-one mapping of filenames. You can use this feature to not change the URL for SEO optimization without renaming the file, for example, if you want all requests to be processed by a single file. A friendly URL is configured in a method of the Startup type ConfigureServices that invokes the RazorPagesOption method of the class AddPageRoute . The following example www.domain.com/product maps a URL to the Razor page "Extras" folder "products.cshtml" file:


public void Configureservices (iservicecollection services) {  Services   . ADDMVC ()   . Addrazorpagesoptions (options =    options. Conventions.addpageroute ("/extras/products", "Product");   }); }

If you have used a friendly URL in Web Forms, you should be aware that AddPageRoute the method's parameter order is the opposite of the Web Forms MapPageRoute method, with the file path as the first parameter. In addition, the AddPageRoute routing template is used as the second parameter, not the route definition, where any constraints are defined separately.

The last example illustrates mapping all requests to a single file. You can do this if the site content is stored in a specific location (database, markdown file), and a single file (such as "index.cshtml") is responsible for locating the content based on the URL and then processing it as HTML:


public void Configureservices (iservicecollection services) {  Services   . ADDMVC ()   . Addrazorpagesoptions (options =     options. Conventions.addpageroute ("/index", "{*url}");  }); }

The route template (*) wildcard means "all". Even with this configuration, the matching rules between existing files on disk and URLs are still working correctly.

Summarize

The routing system in the Razor page is very intuitive, based on the file location, but it is also very powerful and configurable if you need to override the default conventions.

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.