ASP.NET Core introductory note 4, ASP.NET Core MVC routing entry

Knock part, too lazy to all Qiaowan, a direct copy of the chiefs of the blog, if infringement, please inform me as soon as possible amendments to delete

Excerpt from https://www.cnblogs.com/ken-io/p/aspnet-core-tutorial-mvc-route.html

I. Introduction

1. The main contents

  • Principles outlined ASP.NET Core MVC routing work
  • Routing Example ASP.NET Core MVC tape path parameters
  • Routing Example ASP.NET Core MVC front fixing / suffix
  • ASP.NET Core MVC regular expression matching Routes
  • ASP.NET Core MVC routing constraints with a custom route constraint
  • ASP.NET Core MVC RouteAttribute binding routing using presentation

2, this tutorial environmental information

Software Environment Explanation
operating system Windows 10
SDK 2.1.401
ASP.NET Core 2.1.3
HERE Visual Studio Code 1.27
Browser Chrome 69

Benpian code is based on an adjusted: https://github.com/ken-io/asp.net-core-tutorial/tree/master/chapter-02

3, pre-knowledge

You may need to pre-knowledge

  • MVC framework / model description

https://baike.baidu.com/item/mvc

  • Regular Expressions

http://www.runoob.com/regexp/regexp-tutorial.html

Two, ASP.NET Core MVC Routing Overview

1, ASP.NET Core MVC routing works Overview

ASP.NET Core MVC routing role is to apply to the received request to the controller corresponding to handle.

Application of intermediate routes from the start time (RouterMiddleware) was added to the request processing pipeline, and we arranged to load a good route, the route set (the RouteCollection) in. When the application receives the request, it performs the pipeline route matching route (route middleware) and the corresponding request to the controller to process.

In addition, special attention is required to match the order of the route is in the order we define the match from below the top, it is the first to follow the configuration of the first principle in effect.

2, the routing configuration parameters

parameter name Explanation
name Route name can not be repeated
template Routing template, the template may be in the format defined {name} routed parameters
defaults Configuring Routing parameter default values
constraints Routing constraint

In route configuration, MVC framework built two parameters, controller, action.
After matching the route, these two parameters need to be handed over to the current request to Controller + Action corresponding process. Therefore, the lack of any one of these two parameters will lead to routing does not work.
Usually we have two choices:

  • Specifies {controller}, {action} parameter in the template
  • For the controller, action specify a default value in defaults

Three, ASP.NET Core MVC Routes

1, ready to work

For the convenience of our testing, we are ready to undertake the first route Controller & Action

  • Creating TutorialController

Controllers folder in the new controller TutorialController.cs and inherits Controller

using System;
using Microsoft.AspNetCore.Mvc;

namespace Ken.Tutorial.Web.Controllers { public class TutorialController : Controller { } } 
  • Increase Action: Index
public IActionResult Index() { return Content("ASP.NET Core Tutorial by ken from ken.io"); } 
  • Increase in Action: Welcome
public IActionResult Welcome(string name, int age) { return Content($"Welcome {name}(age:{age}) !"); } 

2, the tape path routing parameters

Routing configuration:

routes.MapRoute(
        name: "TutorialPathValueRoute",
        template: "{controller}/{action}/{name}/{age}" ); 

This route adaptation URL:

  • /tutorial/welcome/ken/20

Not fit URL:

  • /tutorial/welcome/ken

If we want to set age not in the path, can also be routed to, you can specify the age is optional, the template {age}modification is {age?}to

routes.MapRoute(
        name: "TutorialPathValueRoute",
        template: "{controller}/{action}/{name}/{age?}" ); 

This route adaptation URL:

  • /tutorial/welcome/ken/20
  • /tutorial/welcome/ken
  • /tutorial/welcome/ken?age=20

3, before routing the fixed suffix

Fixed prefix routing configuration:

routes.MapRoute(
    name: "TutorialPrefixRoute",
    template: "jiaocheng/{action}", defaults: new { controller = "Tutorial" } ); 

This route adaptation URL:

  • / Jiaocheng / index
  • /jiaocheng/welcome

Since the path parameter does not include the controller parameter, it is necessary to specify the default values.

Fixed suffix routing configuration

routes.MapRoute(
    name: "TutorialSuffixRoute",
    template: "{controller}/{action}.html" ); 

This route adaptation URL:

  • /tutorial/index.html
  • /tutorial/welcome.html
  • /home/index.html
  • /home/time.html

Fixed suffix routing is suitable for the demands of the pseudo-static and other
fixed prefix and suffix can be used in combination according to their needs.
Of course, you can also set a fixed value in the intermediate routing template.

Four, ASP.NET Core MVC routing constraints

1. Introduction routing constraints

Routing constraint is mainly used to constrain the routing parameters, then the road to meet the template requirements, check the parameters in the URL format. If the parameter does not satisfy the routing constraints, then still did not match the return route. The most commonly used is probably the parameter type checking, calibration parameter length and the complexity of the verification is satisfied by a positive.

You need to refer to the relevant namespace in Startup.cs before starting

using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Constraints; 

2, constraint length parameter

Routing Configuration: the constraint length can not name> 5

routes.MapRoute(
    name: "TutorialLengthRoute",
    template: "hello/{name}/{age?}", defaults: new { controller = "Tutorial", action = "Welcome", name = "ken" }, constraints: new { name = new MaxLengthRouteConstraint(5) } ); 

This routing adapter

  • /hello
  • /hello/ken
  • /hello/ken/1000

Secondary route is not fit

  • /hello/kenaaaa

We can also configure the routing constraints directly in the template:

routes.MapRoute(
    name: "TutorialLengthRoute2",
    template: "hello2/{name:maxlength(5)}/{age?}", defaults: new { controller = "Tutorial", action = "Welcome", name = "ken" } ); 

3, the constraint parameters

Routing Configuration: the constraint 1 <= age <= 150

routes.MapRoute(
    name: "TutorialLengthRoute",
    template: "hello/{name}/{age?}", defaults: new { controller = "Tutorial", action = "Welcome", name = "ken" }, constraints: new { age = new CompositeRouteConstraint(new IRouteConstraint[] { new IntRouteConstraint(), new MinRouteConstraint(1), new MaxRouteConstraint(150) }) } ); 

This route adaptation:

  • /hello/ken/1
  • /hello/ken/150

This route does not fit

  • /hello/ken/1000

We can also configure the routing constraints directly in the template:

routes.MapRoute(
    name: "TutorialLengthRoute2",
    template: "hello2/{name}/{age:range(1,150)?}", defaults: new { controller = "Tutorial", action = "Welcome", name = "ken" } ); 

4, with the route constraints regex

Routing configuration:

routes.MapRoute(
    name: "TutorialRegexRoute",
    template: "welcome/{name}", defaults: new { controller = "Tutorial", Action = "Welcome" }, constraints: new { name = @"k[a-z]*" } ); 

This route adaptation:

  • /welcome/k
  • /welcome/ken
  • /welcome/kevin

This route does not fit

  • /welcome/k1
  • /welcome/keN
  • /welcome/tom

Here we use regular expression constraint parameter name, you must be regular k[a-z]*by matching, namely: lowercase letter k, and may be followed by zero or more subsequent lowercase letters

We can also configure the routing constraints directly in the template:

routes.MapRoute(
    name: "TutorialRegexRoute2",
    template: "welcome2/{name:regex(@"k[a-z]*")}", defaults: new { controller = "Tutorial", Action = "Welcome" } ); 

5, custom routing constraints

1. Create a custom constraint

Created in the project root directory Common, and in the directory to create a class: NameRouteConstraint.cs, and then implement the interface: IRouteConstraint

using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing; namespace Ken.Tutorial.Web.Common { public class NameRouteConstraint : IRouteConstraint { public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { string name = values["name"]?.ToString(); if (name == null) return true; if (name.Length > 5 && name.Contains(",")) return false; return true; } } } 

Here we name when the constraint length> when 5, name can not contain,

2, routing configuration

The introduction of namespaces

using Ken.Tutorial.Web.Common; 

The introduction of routing constraints ConfigureServices

public void ConfigureServices(IServiceCollection services)
    {
        //引入MVC模块
        services.AddMvc();

        //引入自定义路由约束 services.Configure<RouteOptions>(options => { options.ConstraintMap.Add("name", typeof(NameRouteConstraint)); }); } 

Configuring Routing

routes.MapRoute(
    name: "TutorialDiyConstraintRoute",
    template: "diy/{name}", defaults: new { controller = "Tutorial", action = "Welcome" }, constraints: new { name = new NameRouteConstraint() } ); 

This route adaptation:

  • / Diy / ken
  • / Diy / ken,
  • /diy/kenny

This route does not fit

  • /diy/kenny,

Of course, as usual, you can still configure routing constraints in the template

routes.MapRoute(
    name: "TutorialDiyConstraintRoute2",
    template: "diy2/{name:name}", defaults: new { controller = "Tutorial", action = "Welcome" } ); 

Five, ASP.NET Core MVC bind the routing configuration

1, routing configuration style

  • Centralized Configuration

Centralized routing routing configuration mentioned in the section are carried out in Startup class configuration, routing centralized configuration, except there is no configuration template {controller} parameters are the default for all controllers (Controller) effect. This centralized configuration is generally as long as we configure a default route, otherwise we are not satisfied just by default templates can be configured. In particular, there is no requirement to use the friendly URL, for example: back office systems

  • Distributed placement / configuration Binding of formula

For centralized routing configuration, if a Controller / Action equipped with special routing for reading the code will be less friendly. But never mind, ASP.NET Core MVC also provides RouteAttributeallows us to specify the routing template directly on the Controller or Action.

However, to emphasize that a controller can only choose one routing configuration, if the controller marked RouteAttribute routing configuration, the centralized configuration of the route which will not take effect.

2, binding routing configuration

New TestController.cs inheritance and Controller in Project Controllers heads
and configuration and routing Action

using System;
using Microsoft.AspNetCore.Mvc;

namespace Ken.Tutorial.Web.Controllers { [Route("/test")] public class TestController : Controller { [Route("")] [Route("/test/home")] public IActionResult Index() { return Content("ASP.NET Core RouteAttribute test by ken from ken.io"); } [Route("servertime")] [Route("/t/t")] public IActionResult Time(){ return Content($"ServerTime:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} - ken.io"); } } } 
Configuration Item Explanation
[Route("/test")] It indicates that the Controller access routing prefix / test, must begin with /
[Route("")] Controller arranged to route expressed as a prefix to the access Action; can be /testrouted to the Action
[Route("/test/home")] Controller means to ignore the routing arrangement; it can /test/homebe routed to the Action
[Route("servertime")] Controller arranged to route expressed as a prefix to the access Action; can be /test/servertimerouted to the Action
[Route("/t/t")] Controller means to ignore the routing arrangement; it can /t/tbe routed to the Action

RouteAttribute parameters configured, the equivalent routing template (template) we centralized configuration, and ultimately help us frame or initialized to routing rules to [Route ( "/ test / home")], for example, to generate the equivalent of the following routing configuration:

routes.MapRoute(
    name: "Default",
    template: "test/home", defaults: new { controller = "Test", action = "Index" } ); 

Of course, we can also use the [Route] configuration template parameters, but can still use restraint in the template, custom constraints have no problem.

[Route("welcome/{name:name}")]
public IActionResult Welcome(string name){ return Content($"Welcome {name} !"); } 

The biggest difference is not to define default values, and may not need, and you say it. _

Guess you like

Origin www.cnblogs.com/xiaoahui/p/11723782.html