In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Most people do not understand the knowledge points of this article "how to achieve routing in MVC pattern in ASP.NET Core", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to achieve routing in MVC pattern in ASP.NET Core" article.
1.URL generation
MVC applications can use the URL generation feature of routes to generate URL links to actions (Action). The IUrlHelper interface is used to generate URL and is the basic part between MVC and routing. In the controller, view, and view components, you can find an instance of IUrlHelper through the Url property. In this example, you will use the IUrlHelper interface through the Controller.Url property to generate a URL that points to another operation.
Public class HomeController: Controller {public IActionResult Index () {var url1= Url.Action ("Privacy"); / / Url:Home/Privacy var url2 = Url.Action ("Error"); / / Url:Home/Error var url3 = Url.Action ("Article"); / / Url:Blog/Article var msg = $"url1: {url1}"; msg + = $"\ r\ nurl2: {url2}" Msg + = $"\ r\ nurl3: {url3}"; return Content (msg);} [HttpGet ("custom/url/to/privacy")] / / define a routing template public IActionResult Privacy () {return View ();} public IActionResult Error (string code) {return View (new ErrorViewModel {RequestId = Activity.Current?.Id?? HttpContext.TraceIdentifier});}}
Response result:
If the Url.Action methods only set the Action name, then the IUrlHelper interface gets the Action operation that exists in the current controller and generates the URL. If the Action operates a custom routing template in the current controller, the corresponding routing template URL will be generated. If the Action does not exist in the current controller, an URL with an empty string is generated.
2.URL generation method 2.1 generates URL based on the operation name
Url.Action (IUrlHelper. Action) can generate content to link by specifying the name of the controller (Controller) and the name of the operation (Action). The overloading method also includes adding route value objects, such as Url.Action ("Home", "Index", new {id = 17}), where the route value object is new {id = 17} (the route value object is usually of anonymous type). Let's look at this through an example:
Public class HomeController: Controller {public IActionResult Index (int id) {var url = Url.Action ("Index", "Home", new {id = 17, color = "red", sex = "m"}); return View ();}}
View the generated URL through DEBUG:
2.2 generate URL based on rout
The above code demonstrates how to generate a URL by passing in the controller and operation name. IUrlHelper also provides a series of methods for Url.RouteUrl. These methods are similar to Url.Action, but they do not copy the current values of action and controller to the routing values. The most common use is to specify a route name to generate a URL using a specific route, usually without specifying a controller or operation name.
Public class HomeController: Controller {public IActionResult Index (int id) {var url = Url.RouteUrl ("Privacy_Name"); return View ();} [HttpGet ("custom/url/to/privacy", Name = "Privacy_Name")] / / define a routing template public IActionResult Privacy () {return View ();}}
View the generated URL through DEBUG:
2.3 generate URL in HTML
IHtmlHelper provides HtmlHelper methods Html.BeginForm and Html.ActionLink, which can generate and elements, respectively. These methods use the Url.Action method to generate URL and take similar parameters. The supporting Url.RouteUrl of HtmlHelper is Html.BeginRouteForm and Html.RouteLink, both of which have similar functions.
@ using (Html.BeginForm ("Article", "Blog", FormMethod.Get, new {name = "nForm", id = "idForm"}) {} @ Html.ActionLink ("Article", "Article", "Blog")
View the generated HTML through the browser tool:
2.4 generate URL in the operation result
The above example shows how to use IUrlHelper in a controller. However, the most common use in controllers is to generate URL as part of the result of the operation. The ControllerBase and Controller base classes provide an easy way to reference another operation for the result of the operation. A typical use is to redirect after accepting user input.
Public IActionResult Edit (int id, Customer customer) {if (ModelState.IsValid) {/ / Update DB with new details. Return RedirectToAction ("Index");} return View (customer);} 3. Region (Area)
Areas are ASP.NET functions that provide a way to divide ASP.NET Core Web applications into smaller functional groups, each with its own set of Razor Pages, Controllers, Views, and Models. Zones are actually structures within the application. In an ASP.NET Core Web project, logical components such as Pages, models, controllers, and views are saved in different folders. The ASP.NET Core runtime uses naming conventions to create relationships between these components. For large applications, it may be more advantageous to divide the application into separate advanced functional areas. For example, an e-commerce application with multiple business units, such as checkout, billing, search, and so on. Each unit has its own area to contain views, controllers, Razor Pages, and models. In the following example, we configure the use of default legacy and area routes in MVC based on two business scenarios, purchase (Purchase) and sales (Sale) orders:
Public class Startup {public void Configure (IApplicationBuilder app) {app.UseMvc (routes = > {routes.MapAreaRoute (name: "MyAreaPurchase", areaName: "Purchase", template: "Purchase/ {controller} / {action} / {id?}") Routes.MapAreaRoute (name: "MyAreaSale", areaName: "Sale", template: "Sale/ {controller} / {action} / {id?}"); routes.MapRoute (name: "default", template: "{controller=Home} / {action=Index} / {id?}") / equivalent to / / routes.MapAreaRoute ("purOrder_route", "Purchase", / / "Purchase/ {controller} / {action} / {id?}"); / / routes.MapAreaRoute ("saleOrder_route", "Sale", / / "Sale/ {controller} / {action} / {id?}") / routes.MapRoute ("default", "{controller=Home} / {action=Index} / {id?}");});}}
In the above example, the route value will match the following actions:
[Area ("Purchase")] public class PurOrderController: Controller {public IActionResult Index () {return View ()}} [Area ("Sale")] public class SaleOrderController: Controller {public IActionResult Index () {return View ();}}
Adding an AreaAttribute attribute to each controller indicates that the controller is part of an area, for example, the PurOrderController controller is located in the Purchase area and the SaleOrderController controller is located in the Sale area. The controller without the [Area] attribute is not a member of any area, and cannot be opened when the view under the corresponding controller is opened when the route does not match the area route value. In the above example, only the route values {area = Purchase, controller = PurOrder, action = Index}, {area = Sale, controller = SaleOrder, action = Index} of the view Index listed under the SaleOrderController controller match to open the corresponding link.
4. Implementing routing constraints for IActionConstraint
The easiest way to implement the IActionConstraint constraint is to create a class that derives from System.Attribute and place it on the Action and Controller. MVC automatically discovers any IActionConstraint attributes that are applied as attributes, and constrains the application model application. In the following example, the country selection operation in the routing data is constrained.
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) {string routeDataValue = context.RouteContext.RouteData.Values ["id"] = = null? "": context.RouteContext.RouteData.Values ["id"] .ToString () Return string.Equals (routeDataValue, _ countryCode, StringComparison.OrdinalIgnoreCase);} public class HomeController: Controller {[CountrySpecific ("en-us")] public IActionResult Index (string id) {return View ();}}
According to the official website, IActionConstraint.Order means sequential constraint. For example, there are [CountrySpecific ("en-us")] and [HttpGet] (or other custom attribute constraints) attribute constraints on the HomeController controller, and attribute constraints with lower values are run first. The response results are analyzed by the following table:
Route Url
Result
[SERVICE_NAME] / Home/Index/en-us
two hundred
[SERVICE_NAME] / Home/Index/zh-cn
four hundred and four
As you can see from the above table, in this example, when the Index passes in a route value (en-us) match, the Accept method returns true to indicate that the operation is a match, and then you can open the connection, otherwise the incoming value (zh-cn) does not match.
The above is about the content of this article on "how to achieve routing in MVC mode in ASP.NET Core". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
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.