ASP. NET Core Razor page routing details

  • 2021-10-13 07:11:37
  • OfStack

In the server-side Web application framework, one of the most important designs is how developers match URL with resources on the server to properly handle requests. The easiest way is to map URL to a physical file on disk, as the ASP. NET team did in the Razor page framework.

There are a few rules you must know about how the Razor page framework matches URL to a file, and how to customize the rules to change the output as needed. If you compare the Razor page to the Web Form framework, you also need to understand the replacement Ur l parameters and the mechanism for passing data in URL.

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


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

Rule 2, URL maps to the Razor page, and URL does not contain a file extension.

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

URL 映射文件
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 或者 /Pages/account/index.cshtml

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

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

Page: /account/Index

Page: /account

URL Transfer Parameters

Like most other Framework 1, parameters can be passed in URL as query strings, such as: www.domain.com/product?id=1 ; Alternatively, you can pass it as a routing parameter, so the above example will become www.domain.com/product/1 . Part 1 of URL must be mapped to the parameter name, which is implemented in the routing template of the page ,@page Part 1 of the directive:


@page "{id}"

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


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

Or, you can write to the page's OnGet() Method to add a parameter with the same name as the routing parameter and assign its value to the 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 , so it is realized like this:


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 the BindProperty Property, and omit the OnGet Gets or sets the parameters in the. The contents of the Razor file remain the same, but PageModel The code has changed slightly:


using Microsoft.AspNetCore.Mvc.RazorPages;

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

Constraint

In addition, the constraint of the parameter in this example is that it must have 1 value. URL www.domain.com/product/apple And www.domain.com/product/21 1 is valid, and all of them can match the route. If you want to id Value is an integer, you can specify a constraint by adding a data type to the template:


@page "{id:int}"

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

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


@page "{id:int?}"

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


@page "{id:alpha}"

You can combine it with the minimum length requirement:


@page "{id}"
0

For more constraint information, check the Microsoft documentation.

Friendly URL

Friendly URL can map URL to any file on disk, breaking the 1-to-1 mapping relationship based on file name. You can use this feature to solve the problem that files cannot be renamed without changing URL for SEO optimization, for example, if you want all requests to be processed by one file. Friendly URL in Startup Type of ConfigureServices Method, calling the RazorPagesOption Class AddPageRoute Method. The following example sets the URL www.domain.com/product Map to the Razor page "extras" folder "products. cshtml" file:


@page "{id}"
1

If you have used friendly URL in Web Forms, you should note that AddPageRoute Parameter order of method and Web Forms www.domain.com/product?id=10 Method, with the file path as the first parameter. In addition, AddPageRoute Take the routing template as the second parameter, not the routing definition, where any constraints are defined separately.

The last example shows 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 (for example, "index. cshtml") is responsible for locating the content according to URL and then processing it as HTML:


@page "{id}"
2

The routing template (*) wildcard means "all". Even with this configuration, matching rules between existing files on disk and URL still work.

Summarize

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

Original: "Routing in Razor Pages" https://www.mikesdotnetting.com/article/310/routing-in-razor-pages

Translation: Sweet Tang


Related articles: