Asp.net core razor page routing

Time:2021-5-1

In the server-side Web application framework, one of the most important design is how to match the URL with the resources on the server, so as to correctly handle the request. The simplest way is to map the URL to a physical file on disk, which is how the asp.net team implements in the razor page framework.

There are some rules about how the razor page framework matches URLs to files, and how to customize the rules to change the output results as needed. If you compare a razor page with a web form framework, you also need to understand the URL parameters that are replaced and the mechanism for passing data in the URL.

Rule 1: the razor page needs a root directory. By default, the root directory is pages, which is located in the root directory of the web application project. You can use theStartupClassConfigureServicesMethod to configure another folder 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: 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 Mapping file
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 is mapped to two different files – “account. Cshtml” in the root directory and “index. Cshtml” in the “account” folder. The razor page framework doesn’t recognize which file to select, so if you actually have both files in your application, if you try to browse www.domain.com/account , will throw the following exception:

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

Page: /account/Index

Page: /account

URL delivery parameters

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


@page "{id}"

The 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 values of routing parameters in a variety of ways. The first is to useRouteDataDictionaries:


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

Alternatively, you can send theOnGet()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 usingPageModelThen it is realized 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 use theBindPropertyAnd omit theOnGetMethod. The contents of the razor file remain unchanged, butPageModelCode 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()
  {
  }
 }
}

constraint

In addition, the constraint of the parameter in this example is that it must have a value.URL www.domain.com/product/appleAndwww.domain.com/product/21They are both effective and can match the route. If you want toidIf the value is 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 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 with minimum length requirements:


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

For more constraint information, seeMicrosoft documentation

Friendly URL

Friendly URL can map URL to any file on disk, breaking the one-to-one mapping relationship based on file name. You can use this feature to solve the problem of not changing the URL for SEO optimization without renaming the file, for example, if you want all requests to be processed by one file. Friendly URL inStartupTypeConfigureServicesMethodRazorPagesOptionClassAddPageRoutemethod. The following example shows the URLwww.domain.com/product Map to the “products. Cshtml” file in the “extras” folder of the razor page:


 public void ConfigureServices(IServiceCollection services)
 {
  services
   .AddMvc()
   .AddRazorPagesOptions(options =>
   {
    options.Conventions.AddPageRoute("/extras/products", "product");
   });
 }

If you have used friendly URLs in web forms, you should be aware thatAddPageRouteMethod parameter order and web formsMapPageRouteInstead, the file path is used as the first parameter. In addition,AddPageRouteThe route template is used as the second parameter instead of the route definition, in which any constraint is defined separately.

The final example shows mapping 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 responsible for locating the content according to the URL, and then processing it as HTML, you can perform this operation:


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

The route template (*) wildcard indicates all. Even with this configuration, matching rules between existing files and URLs on disk still work.

summary

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

Original text: routing in razor pageshttps://www.mikesdotnetting.com/article/310/routing-in-razor-pages

Sweet Tang

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.