In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the knowledge of "how to implement strongly typed Routing based on Lamda expressions". Many people will encounter this dilemma in the operation of actual cases, 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!
The basic examples of this approach are as follows:
Services.Configure (opt = > {opt.EnableTypedRouting (); opt.GetRoute ("homepage", c = > c.Action (x = > x.Index ()); opt.GetRoute ("aboutpage/ {name}", c = > c.Action (x = > x.About (Param.Any); opt.PostRoute ("sendcontact", c = > c.Action (x = > x.Contact ());})
As you can see from the example, we can define route through extension methods such as GetRoute or PostRoute, and later use Lambda expressions to determine the type of Controller and the method of Action.
Note that the method name of the Action is obtained here by delegating to execute the Action method (not actually, but based on getting the MethodInfo of the Action).
Realization principle
When configuring services in the ConfigureServices method of Stratup.cs, we can configure the core configuration file MvcOptions used by the MVC site, where this class has an ApplicationModelConventions attribute (List) to save a collection of IApplicationModelConvention interfaces, and the interface can be used to pipeline the program model of the MVC program. The API is defined as follows:
Public interface IApplicationModelConvention
{
Void Apply (ApplicationModel application)
}
The parameter type received by the Apply method in the interface is ApplicationModel, and ApplicationModel has two extremely important contents for us to manipulate, one is the collection of Controller models, and the other is the collection of various Filter. This class is defined as follows:
Public class ApplicationModel {public ApplicationModel (); public IList Controllers {get;} public IList Filters {get;}}
The most important thing here is the ControllerModel class, whose instances hold a variety of important and operable information, such as route definition data on this class and related Action, API description information, routing constraints and so on.
The new IApplicationModelConvention registration method is as follows:
Services.Configure (opt = > {opts.ApplicationModelConventions.Add (new MyApplicationModelConvention ());})
So we can use this method to adjust and modify the whole MVC program model at the right time, and the strongly typed routing in this chapter is implemented by this feature.
Implementation steps
First, define a strongly typed routing model TypedRouteModel class, which inherits from the AttributeRouteModel,AttributeRouteModel class, which is the basic model based on Attribute routing. The code of the TypedRouteModel class is as follows:
Public class TypedRouteModel: AttributeRouteModel {public TypedRouteModel (string template) {Template = template; HttpMethods = new string [0];} public TypeInfo ControllerType {get; private set;} public MethodInfo ActionMember {get; private set;} public IEnumerable HttpMethods {get; private set;} public TypedRouteModel Controller () {ControllerType = typeof (TController). GetTypeInfo (); return this;} public TypedRouteModel Action
The main function of this class is to define and support incoming Controller types and chain calls.
Then define a TypedRoutingApplicationModelConvention class that inherits the IApplicationModelConvention interface. The code is as follows:
Public class TypedRoutingApplicationModelConvention: IApplicationModelConvention
{
Internal static readonly Dictionary
In this class, a static variable Routes is saved to hold all routes declared as Lamda expressions, then look for and modify them in the existing Controllers collection, replace the AttributeRouteModel property, and set the Http Method of the response (if not set, all methods are allowed by default).
Here, we simply replace action.AttributeRouteModel, so it will lead to some defects (for example, an Action can only support one routing path, whichever is *). Students can optimize it according to their own abilities.
When optimizing, note that the Route collection on Controller is saved on the controller.Attributes property, and the Route collection on Action is saved on the action.Attributes property, which can be optimized. Then, on MvcOptions, we add some extension methods to TypeRouteModel for ease of use, as follows:
Public static class MvcOptionsExtensions {public static TypedRouteModel GetRoute (this MvcOptions opts, string template, Action configSetup) {return AddRoute (template, configSetup) .ForHttpMethods ("GET");} public static TypedRouteModel PostRoute (this MvcOptions opts, string template, Action configSetup) {return AddRoute (template, configSetup) .ForHttpMethods ("POST") } public static TypedRouteModel PutRoute (this MvcOptions opts, string template, Action configSetup) {return AddRoute (template, configSetup) .ForHttpMethods ("PUT");} public static TypedRouteModel DeleteRoute (this MvcOptions opts, string template, Action configSetup) {return AddRoute (template, configSetup) .ForHttpMethods ("DELETE");} public static TypedRouteModel TypedRoute (this MvcOptions opts, string template, Action configSetup) {return AddRoute (template, configSetup) } private static TypedRouteModel AddRoute (string template, Action configSetup) {var route = new TypedRouteModel (template); configSetup (route); if (TypedRoutingApplicationModelConvention.Routes.ContainsKey (route.ControllerType)) {var controllerActions = TypedRoutingApplicationModelConvention.Routes [route.ControllerType]; controllerActions.Add (route);} else {var controllerActions = new List {route} TypedRoutingApplicationModelConvention.Routes.Add (route.ControllerType, controllerActions);} return route;} public static void EnableTypedRouting (this MvcOptions opts) {opts.ApplicationModelConventions.Add (new TypedRoutingApplicationModelConvention ());}}
In the above code, we added an EnableTypedRouting extension method to add a new TypedRoutingApplicationModelConvention type example to the MvcOptions.ApplicationModelConventions property.
Other extension methods are used to declare the relevant route. Note that in the initial example, we saw that the method to get action information is to call the action method through delegate (but not actually called), but some methods have parameters, what should we do? To do this, we set a Param class that ignores parameters, with the following code:
Public static class Param {public static TValue Any {get {return default (TValue);}
In this way, when we route the About method with parameters, we can define it this way, with the following code:
Opt.GetRoute ("aboutpage/ {name}", c = > c.Action (x = > x.About (Param.Any)
In addition, since many methods in TypeRouteModel can be called in chains, we can also specify a name for route in this way. The sample code is as follows:
Opt.GetRoute ("homepage", c = > c.Action (x = > x.Index () .WithName ("foo")
At this point, the whole function of strongly typed routing is completed, and there is one more choice when you use it.
Drawbacks (or Bug)
We see that when implementing the IApplicationModelConvention interface above, we simply replace action.AttributeRouteModel, that is, if you already have the Route feature on Action, it will overwrite your information for you, resulting in your route invalidation. For example, if you define a custom route like this:
Public class ProductsController: Controller
{
[Route ("index")]
Public IActionResult Index ()
{
Return Content ("Index")
}
}
Then a strongly typed route is defined through the Lamda expression, with the following code:
Opt.GetRoute ("homepage", c = > c.Action (x = > x.Index ()
So, you can only access it through / homepage, not / index, because it overwrites your Route.
However, the above Lamda expression does not override the Route feature definition defined on Controller, so if you define the Route feature on ProductsController, the two will be combined, for example:
[Route ("products")] public class ProductsController: Controller {public IActionResult Index () {return Content ("Index");}}
Then your URL should be / products/homepage, not / homepage. But if your code in the Lamda expression looks like this:
Opt.GetRoute ("/ homepage", c = > c.Action (x = > x.Index ()
Then your URL should be / homepage, because the routing character is the absolute path / homepage, not homepage.
That's all for "how to implement strongly typed Routing based on Lamda expressions". 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.