Home Web Front-end JS Tutorial A detailed introduction to ASP.NET Core Razor page routing

A detailed introduction to ASP.NET Core Razor page routing

Sep 05, 2017 am 11:05 AM
asp.net core

This article mainly introduces the detailed explanation of ASP.NET Core Razor page routing. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look

In the server-side Web application framework, a very important design is how developers match URLs with resources on the server in order to correctly handle requests. The simplest way is to map the URL to a physical file on disk, which is how the ASP.NET team implements it in the Razor Pages framework.

There are some rules you must know about how the Razor Pages framework matches URLs to files, and how you can customize the rules to change the output as needed. If you are comparing Razor Pages to the Web Forms framework, you also need to understand the substituted URL parameters and the mechanism for passing data in the URL.

Rule 1, Razor pages need a root directory. By default, this root directory is Pages, located in the root directory of the web application project. You can configure other folders as the root directory in the ConfigureServices method of the Startup class. The following is to change the root directory to be located in the application "Content" folder:


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

Rule two, the URL is mapped to the Razor page, the URL does not contain the file extension .

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

URLmaps the 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

在最后一个例子中,URL映射到两个不同的文件 - 根目录中的“account.cshtml”、“account”文件夹中的“index.cshtml”。Razor 页面框架无法识别要选择哪一个文件,因此如果您在应用程序中实际同时拥有这两个文件,那么如果您尝试浏览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传递参数

就像大多数其它框架一样,参数可以作为查询字符串在 URL 中传递,例如:www.domain.com/product?id=1;或者,您可以将其作为路由参数传递,因此上述示例将变为www.domain.com/product/1。URL的一部分必须映射到参数名称,在页面的路由模板来实现的,@page指令的一部分:


@page "{id}"
Copy after login

该模板告诉框架将页面名称之后URL的第一段作为“id”的路由参数。您可以通过多种方式访问路由参数的值。第一个是使用RouteData字典:


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

或者,您可以向该页面的OnGet()方法添加与路由参数相同名称的参数,并将其值分配给公共属性:


@page "{id}"
@{
 @functions{

  public int Id { get; set; }

  public void OnGet(int id)
  {
   Id = id;
  }
 }
}

The Id is @Id

Copy after login

如果您使用的是PageModel,那么是这样实现的:


using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPages.Pages
{
 public class ProductModel : PageModel
 {
  public int Id { get; set; }
  public void OnGet(int id)
  {
   Id = id;
  }
 }
}
Copy after login


@page "{id}"
@model ProductModel

The Id is @Model.Id

Copy after login

最后,您可以在公有属性使用BindProperty特性,并省略该OnGet方法中的参数。Razor 文件内容保持不变,但是PageModel代码略有更改:


using Microsoft.AspNetCore.Mvc.RazorPages;

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

约束

此外,在此示例中参数的约束是它必须有一个值。URL www.domain.com/product/applewww.domain.com/product/21一样有效,都是可以与路由匹配。如果您希望id值为整数,则可以通过将数据类型添加到模板来指定约束:


@page "{id:int}"
Copy after login

现在,如果您尝试通过“apple”作为参数值,应用程序将返回404 Not Found状态码。

您可以指定值不是必需的,可以将参数设置为可为空类型:


@page "{id:int?}"
Copy after login

如果您的应用程序允许使用“apple”作为参数值,则可以指定只允许使用A-Z和a-z的字符:


@page "{id:alpha}"
Copy after login

您可以与最小长度要求相结合:


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

更多的约束信息,可以查看微软文档。

友好URL

友好的URL能够将 URL 映射到磁盘上的任意文件,打破根据文件名一对一的映射关系。您可以使用这个特性来不改变 URL 以进行SEO优化而不能重命名文件的问题,例如,如果希望所有请求由一个文件进行处理。友好 URL 在Startup类型的ConfigureServices方法中配置,调用RazorPagesOption类的AddPageRoute方法。以下示例将 URL www.domain.com/product 映射到Razor 页面 “extras”文件夹“products.cshtml”文件:


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

如果您在 Web Forms 中使用过友好 URL,则应注意AddPageRoute方法的参数顺序与 Web Forms MapPageRoute方法相反,文件路径作为第一个参数。此外,AddPageRoute将路由模板作为第二参数,而不是路由定义,其中任何约束被单独定义。

最后一个例子说明将所有请求映射到单个文件。如果站点内容存储在特定位置(数据库,Markdown文件),并且由单个文件(例如 “index.cshtml” )负责根据 URL 定位内容,然后将其处理为HTML,则可以执行此操作:


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

路由模板(*)通配符表示“全部”。即使使用此配置,磁盘上的现有文件和URL之间的匹配规则仍然正常运行。

总结

Razor 页面中的路由系统非常直观,基于文件位置,但如果需要覆盖默认约定,它也非常强大,可配置。

原文:《Routing in Razor Pages》https://www.mikesdotnetting.com/article/310/routing-in-razor-pages

The above is the detailed content of A detailed introduction to ASP.NET Core Razor page routing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to enable Core Isolation's memory integrity feature in Windows 11 How to enable Core Isolation's memory integrity feature in Windows 11 May 10, 2023 pm 11:49 PM

Microsoft's Windows 11 2022 Update (22H2) enables CoreIsolation's memory integrity protection by default. However, if you are running an older version of the operating system, such as Windows 11 2022 Update (22H1), you will need to turn this feature on manually. Turn on CoreIsolation's Memory Integrity feature in Windows 11 For users who don't know about Core Isolation, it's a security process designed to protect basic core activities on Windows from malicious programs by isolating them in memory. This process, combined with the memory integrity feature, ensures

What does computer core mean? What does computer core mean? Sep 05, 2022 am 11:24 AM

Core has two meanings in computers: 1. The core, also known as the core, is the most important component of the CPU. All calculations, accepting storage commands, and processing data of the CPU are performed by the core; 2. Core, core is Intel's processor Name, Core is the processor brand launched by Intel after the Pentium processor. It has currently released twelfth generation Core processors.

How to Fix Processor Thermal Trip Error in Windows 11/10 [Fix] How to Fix Processor Thermal Trip Error in Windows 11/10 [Fix] Apr 17, 2023 am 08:13 AM

Most of the devices, such as laptops and desktops, have been heavily used by young gamers and coders for a long time. The system sometimes hangs due to application overload. This forces users to shut down their systems. This mainly happens to players who install and play heavy games. When the system tries to boot after force shutdown, it throws an error on a black screen as shown below: Below are the warnings detected during this boot. These can be viewed in the settings on the event log page. Warning: Processor thermal trip. Press any key to continue. ..These types of warning messages are always thrown when the processor temperature of a desktop or laptop exceeds its threshold temperature. Listed below are the reasons why this happens on Windows systems. Many heavy applications are in

.NET Core cross-platform application development practice: a seamless journey from Windows to Linux and macOS .NET Core cross-platform application development practice: a seamless journey from Windows to Linux and macOS Feb 26, 2024 pm 12:55 PM

With the launch of .NETCore, .NET developers have a new opportunity to easily write and run .NET applications on multiple operating systems. This article will delve into how to use .NETCore to achieve cross-platform application development, and share best practice experience on operating systems such as Windows, Linux, and macOS. 1. Prepare the development environment. To start cross-platform application development, you first need to prepare the development environment for each target platform. Windows On Windows, you can install .NETCoreSDK through Visual Studio. After installation is complete, you can create and run .NETCore projects through Visual Studio. Li

Is CORE coin worth holding for the long term? Is CORE coin worth investing in? Is CORE coin worth holding for the long term? Is CORE coin worth investing in? Feb 29, 2024 pm 05:34 PM

CORE coin: Is it worth holding for the long term? CORE coin is a cryptocurrency based on the Proof of Work (PoW) consensus mechanism and was founded by the Core team in 2018. Its goal is to establish a secure, efficient, and scalable digital currency system that is widely used for payment and value storage. CORE coin is designed to provide a decentralized payment solution that provides users with more privacy protection and transaction convenience. Advantages and security of CORE currency: CORE currency is based on the workload proof consensus mechanism and has strong security. Efficient: CORE coin’s transaction speed is fast and can handle thousands of transactions per second. Scalable: CORE coin has a large block capacity and can support a large number of transactions. Decentralization: CORE coin is a decentralized cryptocurrency

What is core under linux What is core under linux Mar 23, 2023 am 10:00 AM

Under Linux, core is a memory image with debugging information added. When a program exits or terminates abnormally under Linux, we will use the core file for analysis, which contains information such as memory, registers, stack pointers and other information when the program is running. The format is ELF, which can be understood as dumping the current status of the program into a file.

IFA 2024 | Core Ultra Series 2: In Lunar Lake, Intel introduces its most efficient x86 CPU yet IFA 2024 | Core Ultra Series 2: In Lunar Lake, Intel introduces its most efficient x86 CPU yet Sep 04, 2024 am 06:38 AM

Roughly one year after announcing the Core Ultra Series 1, also known as Meteor Lake, Intel follows up with the second generation. Core Ultra Series 2 aka Lunar Lake was already introduced at June's Computex. At IFA, the final launch of the Core Ultr

IFA 2024 | Core Ultra Series 2: With Lunar Lake, Intel introduces its most efficient x86 CPU yet IFA 2024 | Core Ultra Series 2: With Lunar Lake, Intel introduces its most efficient x86 CPU yet Sep 05, 2024 am 02:10 AM

Roughly one year after announcing the Core Ultra Series 1, also known as Meteor Lake, Intel follows up with the second generation. Core Ultra Series 2 aka Lunar Lake was already introduced at June's Computex. At IFA, the final launch of the Core Ultr

See all articles