In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the relevant knowledge of "how to use ASP.NET Core MVC routing". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
ASP.NET Core MVC routing is based on ASP.NET Core routing, a powerful URL mapping component that can build applications that understand and search for web addresses. This allows us to customize the URL naming form of the application so that it works well in search engine optimization (SEO) and link generation, regardless of how the files on the Web server are organized. We can easily use route template syntax to define routes, and route template syntax supports route value constraints, default values and optional values.
Constraint-based routing allows you to globally define the URL formats supported by the application and how these formats map to a specified method of operation (Action) in a given controller. When a request is received, the routing engine parses the URL and matches it to a defined URL format, and then invokes the relevant controller operation methods.
Routes.MapRoute (name: "default", template: "{controller=Home} / {action=Index} / {id?}")
Feature routing (Attribute Routing) allows you to define the routing of an application by specifying routing information in a way that adds features to the controller and method. This means that route definitions are adjacent to the controllers and methods with which they are associated.
ASP.NET Core MVC uses routing middleware to match the URL of incoming requests and map them to operational methods. The route is defined in the startup code or attribute, which describes how the URL path should match the action method, and is used to generate a link in the response and send it.
1. Set up routing middleware
Create an ASP.NET Core Web application, which is in the Configure method of the Startup class:
App.UseMvc (routes = > {routes.MapRoute (name: "default", template: "{controller=Home} / {action=Index} / {id?}");})
During the call to UseMvc, MapRoute is used to create a single route, the default route. Most MVC applications use routes similar to the default route template.
The route template {controller=Home} / {action=Index} / {id?} can match the URL path like Blog/Details/5 and extract the route value {controller=Blog,action=Details,id=5}. MVC will try to find a controller named BlogController and run the action method.
{controller=Home} defines Home as the default controller
{action=Index} define Index as the default action
{id?} define id as optional
The default and optional path parameters may not appear in the URL path that needs to be matched.
Using the {controller=Home} / {action=Index} / {id?} template, you can HomeController.Index the following URL paths:
/ Home/Index/7
/ Home/Index
/ Home
/
There is a simple method app.UseMvcWithDefaultRoute () that replaces the above method.
Both UseMvc and UseMvcWithDefaultRoute add an instance of RouteMiddleware to the middleware pipeline. Instead of interacting directly with the middleware, MVC uses routing to process requests. MVC links to the route through an instance of MvcRouteHandler. The following code is similar to UseMvc:
Var route = new RouteBuilder (app); / / add a connection to MVC, call back route.DefaultHandler = new MvcRouteHandler (...) by calling MapRoute; / / perform a callback to register routing route.MapRoute ("default", "{controller=Home} / {action=Index} / {id?}") / / create route sets and add them to the middleware app.UseRouter (route.Build ())
UseMvc does not define any routes directly, it adds a placeholder to the collection of routes for attribute routes. Reloading UseMvc allows us to add our own routes and also supports attribute routing. UseMvc and all its variants add placeholders to attribute routing, which makes attribute routing always available. UseMvcWithDefaultRoute defines a default route and supports attribute routing.
two。 General routing
Routes.MapRoute (name: "default", template: "{controller=Home} / {action=Index} / {id?}"); this is a regular route because it establishes a contracted URL path:
The first path segment is mapped to the controller name
The second path is mapped to the operation name
The third section is the optional id for mapping to model entities
With default routing, the URL path / Blog/Index is mapped to the BlogController.Index operation. The mapping is based on controller and operation names, not on namespaces, source file locations, and so on.
Using a default route for regular routes allows you to quickly build an application without having to define a route for each operation. For CRUD-style applications, the URL of the entire controller is consistent.
3. Multiple routing
You can add multiple routes in UseMvc by adding MapRoute. This allows you to define multiple conventions or to add general routes dedicated to specific operations:
App.UseMvc (routes = > {routes.MapRoute ("blog", "blog/ {* article}", defaults: new {Controller = "Blog", Action = "Index"}); routes.MapRoute (name: "default", template: "{controller=Home} / {action=Index} / {id?}") })
The blog route here is a dedicated regular route, which means that it does not use a regular routing system, but is dedicated to a specific action. This route always maps to BlogController.Index.
The routes in the route collection are ordered and processed in the order in which they are added.
1. Fallback
As part of request processing, MVC verifies that routing values can be used to find controllers and operations in the application. If the route value does not match the operation, then the route is considered mismatched and the next route will be tried. This process is called fallback because regular routes overlap.
two。 Action ambiguity
When two consistent operations are routed, the MVC must disambiguate and choose the best action, or an exception will be thrown. For example:
Public class BlogController: Controller {public ActionResult Edit (int id) {return View ();} [HttpPost] public ActionResult Edit (int id, IFormCollection collection) {try {/ / TODO: Add update logic here return RedirectToAction (nameof (Index)) } catch {return View ();}
URL / Blog/Edit/7 can match these two actions, which is a typical pattern of MVC controllers, where Edit (int) is used to display edited forms and Edit (int,IFormCollection) is used to process submitted forms. To achieve this, MVC needs to choose Edit (int,IFormCollection) when HTTP POST and Edit (int) when other HTTP verbs.
HttpPostAttribute is an implementation of IActionConstraint that allows you to choose an action only if the HTTP verb is POST. The existence of IActionConstraint makes Edit (int,IFormCollection) better matching than Edit (int).
If more than one route matches and MVC cannot find the best route, an AmbiguousActionException exception is thrown.
3. Route name
In the above example, the "blog" and "default" strings are route names, which provide a logical name for routes so that named routes can be used to generate URL. The name of the route must be unique within the scope of the application.
The route name has no effect on the processing of URL matches or requests, only for URL generation.
4. Routing characteristic
Property routing uses a set of features to map actions directly to the routing template. Next, app.UseMvc () is called in Configure; there is no delivery route.
Public class HomeController: Controller {[Route (")] [Route (" Home ")] [Route (" Home/Index ")] public IActionResult Index () {return View ();} [Route (" Home/About ")] public IActionResult About () {ViewData [" Message "] =" Your application description page. " Return View ();}}
The HomeController.Index operation will be performed on any URL access to /, / Home or / Home/Index.
Feature routes require more input to specify a route, while regular routes are more concise when dealing with routes. However, feature routing allows precise control of the routing template for each operation.
The routing parameters for action,area and controller are not defined in the above template. In fact, these parameters are not allowed in feature routes, because the route template already has an operation associated with it, and it makes no sense to parse the operation name in URL.
Feature routing can also use HTTP [verb] features, such as HTTPPost:
[HttpGet ("/ Blog")] public ActionResult Index () {return View ();
Because feature routing is suitable for specific operations, it is easy to make parameters a necessary part of the template definition. In the following example, id is a necessary part of URL:
[HttpGet ("Blog/Edit/ {id}")] public ActionResult Edit (int id) {return View ();}
Regular default routes define id parameters as optional ({id?}), while feature routes are required parameters, which can be precisely specified, such as packets / Blog/Get and / Blog/Get/ {id} assigned to different operations.
5. Combined routing
In order to reduce the repetitive part of the characteristic routing, the routing characteristics on the controller are combined with the routing characteristics on each operation. Any routing template defined on the controller is prefixed as the operation routing template.
[Route ("blog")] public class BlogController: Controller {[HttpGet] public ActionResult GetAll () {return View ();} [HttpGet ("{id}")] public ActionResult GetById (int id) {return View ();}}
/ blog matches the GetAll method and / blog/1 matches the GetById method.
Note that if the routing template starts with / on the operation, it will not be combined with the routing template on the controller.
6. Order of characteristic rout
Whereas regular routes are performed in a defined order, characteristic routes build a tree structure that matches all routes at the same time. It looks as if the route entries are placed in an ideal order, and the most specific routes are performed before the normal routes. For example, routing blog/Edit/4 is more specific than blog/ {* article}.
Feature routing uses the Order attribute specific to all the routes provided by the framework to configure the order and processes the route according to the ascending order of the Order attribute. The default is 0, and a setting of-1 executes before there is no set route.
7. Tag replacement in routing templates ([controller], [action], [area])
For convenience, feature routing supports tag substitution, that is, replacing the corresponding name by enclosing a tag ([,]) in square brackets. The tags [action], [area] and [controller] will be replaced with the operation name, zone domain name and controller name corresponding to the operation.
[Route ("[controller] / [action]")] public class BlogController: Controller {[HttpGet] / / matching Blog/GetAll public ActionResult GetAll () {return View ();}}
Tag replacement occurs in the last step of building a feature route. In the same way as the above result:
Public class BlogController: Controller {[HttpGet ("[controller] / [action]")] / / match Blog/GetAll public ActionResult GetAll () {return View ();}}
Feature routing can also be combined with inheritance, that is, inheriting the route tag of the parent class.
Feature routing supports a single operation to define a route. If multiple routing features implemented with IActionConstarint are defined on a single operation, each operation constraint is combined with the routing defined by the attribute:
[Route ("Store")] [Route ("[controller]")] public class BlogController: Controller {[HttpGet ("GetAll")] / / matches Get Blog/GetAll and Store/GetAll [HttpPost ("Set")] / / matches Post Blog/Set and Store/Set public ActionResult GetAll () {return View ();}}
While using multiple routes to a single operation may seem powerful, it is best to keep the URL space simple and well-defined. Use multiple routes to operate only when there is a special need, such as supporting multiple clients.
8. Use IRouteTemplateProvider custom routing features
Routing features provided by all frameworks ([Route (...)], [HttpGet (...)] Etc.) all implement IRouteTemplateProvider interface. When the program starts, MVC looks up the controller classes and operation methods that implement the characteristics of the IRouteTemplateProvider interface to build a set of time-saving routes.
You can define your own routing features by implementing IRouteTemplateProvider. Each IRouteTemplateProvider allows you to define a single route that uses a custom route template, order, and name:
Public class MyApiControllerAttribute:Attribute, IRouteTemplateProvider {public string Template = > "api/ [controller]"; public int? Order {get; set;} public string Name {get; set;}}
When the [MyApiController] feature is applied, the Template is automatically set to api/ [controller].
9. Use the application model to customize feature routing
The object model that is created when the application model is started, which contains all the metadata that MVC uses to route and perform operations. The application model includes all data collected from routing features (via IRouteTemplateProvider). We can write conventions to modify the application model at startup as a custom routing behavior.
Public class NamespaceRoutingConvention:IControllerModelConvention {private readonly string _ baseNamespace; public NamespaceRoutingConvention (string baseNamespace) {_ baseNamespace = baseNamespace;} public void Apply (ControllerModel controller) {var hasRouteAttributes = controller.Selectors.Any (selector = > selector.AttributeRouteModel! = null) If (hasRouteAttributes) {/ / this controller customizes some routes, so it is considered to override return } / / use namespaces and controllers to infer the route of the controller / Example: / controller.ControllerTypeInfo-> "My.Application.Admin.UsersController" / / baseNamespace-> "My.Application" / / template = > "Admin/ [controller]" / this makes your routing roughly consistent with your project structure / / var namespc = controller.ControllerType.Namespace Var template = new StringBuilder (); template.Append (namespc,_baseNamespace.Length+1,namespc.Length- _ baseNamespace.Length-1); template.Replace ('.','/'); template.Append ("/ [controller]") Foreach (var selector in controller.Selectors) {selector.AttributeRouteModel = new AttributeRouteModel () {Template = template.ToString ()};}
How to use this part, the individual is still not very clear, here is only a record of the official documents, who knows can tell the following younger brother.
10.URL generation
MVC applications can use the generation feature of routing URL to generate URL links to operations. Generating URL eliminates hard-coding URL, making the code more robust and maintainable. The IUrlHelper interface is the basic block of the infrastructure between MVC and the generation of URL routes. You can find an available IUrlHelper instance through the URL property in the controller, view, and view components:
Public class HomeController: Controller {public IActionResult Index () {/ / generate / Home/Contact var url = Url.Action ("Contact"); return View ();} public IActionResult Contact () {ViewData ["Message"] = "Your application description page."; return View ();}}
This URL path is created by a route that combines the route value with the current request and passes the value to Url.Action, replacing the corresponding value in the routing template.
The example of Url.Action (above is regular routing, but the generation of URL is similar to feature routing, although the concept is different. In a regular route, the route value is used to extend the template, and the route values for controller and action usually appear in that template, because the URL that matches the route adheres to a convention. In feature routing, route values for controller and action are not allowed in templates-they are used to find which template should be used, for example:
/ / modify Configurepublic void Configure (IApplicationBuilder app, IHostingEnvironment env) {app.UseMvc ();} public class HomeController: Controller {[HttpGet ("/")] public IActionResult Index () {/ / generate / Home/To/About var url = Url.Action ("About"); return View () [HttpGet ("Home/To/About")] public IActionResult About () {ViewData ["Message"] = "Your application description page."; return View ();}}
MVC builds a lookup table for all feature routing operations and matches the controller and action values to select the routing template for generating URL.
11. Generate URL by operation name
Url.Action (this IUrlHelper helper, string action) and all related overloads specify what to link based on the specified controller name and operation name.
When using Url.Action, the current route values for controller and action are specified-- the values of controller and action are both part of the environment value and value. The Url.Action method always uses the current values of controller and action and generates a URL path routed to the current operation.
The route attempts to populate the information with the value in the environment value, and we can also specify the routing parameters:
Public class HomeController: Controller {public IActionResult Index () {/ / Blog/Edit/1 var url = Url.Action ("Edit", "Blog", new {id=1}); / / generate / Blog/Edit/1?color=red var url1 = Url.Action ("Edit", "Blog", new {id=1, color= "red"}); return View () }}
If you want to create an absolute URL, you can use an overload that accepts protocol: Url.Action ("Edit", "Blog", new {id=1}, protocol:Request.Scheme)
twelve。 Generate URL by route name
IUrlHelper also provides a series of methods for Url.RouteUrl, the most common of which is to specify a route name to generate URL using a specific route, usually without specifying a controller name or operation name:
Public class HomeController: Controller {public IActionResult Index () {/ / generate customer/to/url var url = Url.RouteUrl ("AboutRoute"); return View ();} [HttpGet ("customer/to/url", Name = "AboutRoute")] public IActionResult About () {ViewData ["Message"] = "Your application description page." Return View ();}}
The URLHtmlHelper generated in HTML provides the HtmlHelper methods Html.BeginForm and Html.ActionLink to generate and elements, respectively. These methods use the Url.Action method to generate a URL, and they accept similar parameters. Url.RouteLink, they have similar functions. TagHelper generates URL through form and TagHelper. These all use IUrlHelper as their implementation. In the inner view, IUrlHelper generates any specific URL that does not contain the above through the Url attribute.
13. Generate URL in the operation result
A common use in controllers is to generate a URL as part of the result of the operation. The Controller and ControllerBase base classes provide simple methods for referencing the results of other operations. A typical method:
Public class HomeController: Controller {public IActionResult Index () {/ / generate customer/to/url var url = Url.RouteUrl ("AboutRoute"); return Redirect (url); / / or / return RedirectToAction ("Contact") [HttpGet ("customer/to/url", Name = "AboutRoute")] public IActionResult About () {ViewData ["Message"] = "Your application description page."; return View ();} public IActionResult Contact () {ViewData ["Message"] = "Your contact page."; return View ();}}
The RedirectToAction method has multiple overloads to use.
14. Special case of dedicated regular routin
There is a special type of route called private regular route. The following route is named blog:
App.UseMvc (routes = > {routes.MapRoute ("blog", "blog/ {* article}", defaults: new {Controller = "Blog", Action = "Index"}); routes.MapRoute (name: "default", template: "{controller=Home} / {action=Index} / {id?}") })
Url.Action ("Index", "Home") generates URL using the default route.
Private regular routing is a special behavior that relies on the default route, and there are no corresponding routing parameters to prevent the route from generating URL "too greedy". When a route performs URL generation, the supplied value must match the default value; otherwise, URL generation using blog fails because the value {controller=Home,action=Index} does not match {controller=Blog,action=Index}. Then the route fallback attempts default and succeeds.
15. Region
Areas is a MVC feature that organizes related functions into a group as a separate routing namespace (for controller operations) and a folder structure (for views). Using zones allows applications to have multiple controllers with the same name-- as long as they have different zones. Using an area creates a hierarchy for routing purposes by adding another routing parameter to the controller and operation.
Configure MVC with a default regular route and name a route for an OMS area:
App.UseMvc (routes = > {routes.MapAreaRoute ("oms", "OMS", "OManage/ {controller} / {action} / {id?}", defaults: new {Controller = "Order", Action = "Index"}) Routes.MapRoute (name: "default", template: "{controller=Home} / {action=Index} / {id?}");}); namespace Blog.Areas.OMS.Controllers {[Area ("OMS")] public class OrderController: Controller {/ / GET: Order public ActionResult Index () {return View () }}
When URL is / OManage/Order/Edit, the route value {area = OMS,controller = Order, action = Edit} is matched. The area route value is generated from the area default value. You can also use the MapRoute method to:
Routes.MapRoute ("oms", "OManage/ {controller} / {action} / {id?}", defaults:new {area= "OMS"}, constraints:new {area= "OMS"})
MapAreaRoute creates a route, using both the default route and the area constraint, which uses the supplied area name OMS. The default value guarantees that the route always handles {area = OMS}, and the constraint requires the value {area = OMS} for URL generation.
Regular routes are sequentially dependent. General area routes are placed in front because area routes are more specific.
AreaAttribute indicates that the controller is part of an area, that is, the controller is in the OMS area. The controller does not belong to any area without the [Area] feature.
When an operation is performed within an area, the routing value of the area is used as the environment value for URL generation, which means that by default, the region is sticky to URL generation:
Namespace Blog.Areas.OMS.Controllers {[Area ("OMS")] public class OrderController: Controller {/ / GET: Order public ActionResult Index () {/ / generate / OManage/Home/Create var url = Url.Action ("Create", "Home"); / / generate / Home/Create var url1 = Url.Action ("Create", "Home", new {area= ""}) Return View ();} 16.IActionConstraint
In general, applications do not need to customize the IActionConstraint, [HttpGet] attributes, and similar features to implement the IActionConstraint interface to restrict the execution of methods.
When two operations are identical and one of them uses IActionConstraint, it is always considered better than an operation that is not in use, because it is considered more specific, and both operations can be selected when matching. (unused operations match any HTTP predicate)
Conceptually, IActionConstraint is a form of overload, but not an overload with the same name, it is an overload that matches the same URL operation. Feature routing also uses IActionConstraint, and can cause operations of different controllers to be considered candidate operations.
The easiest way to implement IActionConstraint is to create a class that derives from System.Attribute and place it on the operation and controller. MVC automatically discovers any IActionConstraint that is applied as a feature. You can use the program model to apply constraints, which is probably the most flexible approach because it allows metaprogramming of how they are applied.
As an example, a constraint selects a country code operation based on routing data:
Public class CountrySpecificAttribute:Attribute,IActionConstraint {private readonly string _ countryCode; public CountrySpecificAttribute (string countryCode) {_ countryCode = countryCode;} public int Order {get {return 0 } public bool Accept (ActionConstraintContext context) {return string.Equals (context.RouteContext.RouteData.Values ["country"] .ToString (), _ countryCode,StringComparison.OrdinalIgnoreCase);}}
The Accept method returns true, indicating that the operation matches when the country route values match. This is different from RouteValueAttribute because it allows you to fall back to a non-feature operation. This example shows that if you define an en-US operation and then the country code is fr-FR, you fall back to a more generic controller that does not have [CountrySpecific (...)] applied.
The Order attribute, like the Order attribute in the [HttpGet] attribute, is used to determine the order in which to run.
That's all for the content of "how to use ASP.NET Core MVC routing". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.