Detailed explanation of ASP. NET Core Razor page routing, corerazor

Source: Internet
Author: User

Detailed explanation of ASP. NET Core Razor page routing, corerazor

In the server-side Web application framework, a very important design is how developers can match URLs with resources on the server to process requests correctly. The simplest method is to map URLs to physical files on the disk. In the Razor page framework, the ASP. NET team implements this.

For more information about how the Razor page framework matches URLs with files, see some rules and how to customize rules to change output results as needed. If you compare the Razor page with the Web Form framework, you also need to understand the replaced Ur l parameter and the mechanism for passing data in the URL.

Rule 1: 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 canStartupClassConfigureServicesTo configure other folders as the root directory. Change the root directory to the "Content" folder of the application:

 public void ConfigureServices(IServiceCollection services) {   services    .AddMvc().    AddRazorPagesOptions(options => {     options.RootDirectory = "/Content";   });  }

Rule 2: The URL is mapped to the Razor page, and the URL does not contain the file extension.

Rule 3: "Index. cshtml" is a default document, which means that if

URL Ing File /Pages/Index. cshtml /Pages/Index. cshtml /Pages/Index. cshtml /Pages/account. cshtml or/Pages/account/index. cshtml

In the last example, the URL is mapped to two different files-"index. cshtml" in the "account. cshtml" and "account" folders in the root directory ". The Razor page framework cannot identify which file to select. Therefore, if you actually own both files in the application, if you attempt to browse, the following exception will be thrown:

AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:



URL Transfer Parameters

Like most other frameworks, parameters can be passed as query strings in URLs. For, you can pass it as a route parameter, so the above example will A part of the URL must be mapped to the parameter name.,@pagePart of the command:

@page "{id}"

This template tells the framework to use the first segment of the URL after the Page name as the routing parameter of "id. You can access the value of Route parameters in multiple ways. The first is to useRouteDataDictionary:

@page "{id}"{ var productId = RouteData.Values["id"];}

Alternatively, you canOnGet()Method to add a parameter with the same name as the routing parameter and assign its value to the public attribute:

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

If you are usingPageModelIs implemented as follows:

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 useBindPropertyFeature, and omit thisOnGetParameters in the method. The content of the Razor file remains unchanged,PageModelCode slightly changed:

using Microsoft.AspNetCore.Mvc.RazorPages;namespace RazorPages.Pages{ public class ProductModel : PageModel {  [BindProperty(SupportsGet = true)]  public int Id { get; set; }  public void OnGet()  {  } }}


In this example, the parameter constraint is that it must have a value.URL is equally valid and can be matched with the route. If you wantidIf the value is an integer, you can specify the constraints by adding the data type to the template:

@page "{id:int}"

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

You can specify a value that is not required. You can set the parameter type to NULL:

@page "{id:int?}"

If your application allows the use of apple as a parameter value, you can specify characters that only allow the use of A-Z and a-z:

@page "{id:alpha}"

You can combine with the minimum length requirement:

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

For more constraints, see the Microsoft documentation.

Friendly URL

A friendly URL maps a URL to any file on the disk, breaking the one-to-one ing relationship based on the file name. You can use this feature to not change the URL for SEO optimization but not rename the file. For example, if you want all requests to be processed by one file. Friendly URL inStartupTypeConfigureServicesMethod Configuration, callRazorPagesOptionClassAddPageRouteMethod. In the following Map to the "products. cshtml" file in the "extras" folder on the Razor page:

 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, note thatAddPageRouteMethod Parameter order and Web FormsMapPageRouteOn the contrary, the file path is the first parameter. In addition,AddPageRouteThe routing template is used as the second parameter rather than the routing definition, and any constraints are defined separately.

The last example illustrates how to map all requests to a single file. If the site content is stored in a specific location (Database, Markdown file), and a single file (such as "index. cshtml) is used to locate the content based on the URL and process the content as HTML. You can perform this operation:

 public void ConfigureServices(IServiceCollection services) {  services   .AddMvc()   .AddRazorPagesOptions(options => {     options.Conventions.AddPageRoute("/index", "{*url}");  }); }

The wildcard character "all" in the routing template ". Even with this configuration, the matching rules between existing files and URLs on the disk still run normally.


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

Routing in Razor Pages

Translation: Sweet Tang

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: 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.