In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces how to use ASP.NETCoreMVC to configure global routing prefixes, the content is very detailed, interested friends can refer to, hope to be helpful to you.
ASP.NET Core MVC configure global routing prefix
Hello, everyone. Today, I would like to introduce a new feature of ASP.NET Core MVC, which adds a unified prefix to global routing. Strictly speaking, it's not a new feature, but it's unique to Core MVC.
Application background
I wonder if you have ever encountered this scenario when you are working on Web Api applications, that is, all interfaces start with / api, that is, our api API requests addresses like this:
Http://www.example.com/api/order/333
Or such a need.
Http://www.example.com/api/v2/order/333
In the past, if we wanted to implement this requirement, we could add a [Route ("/ api/order")] feature routing Attribute to Controller, and then the MVC framework would scan your routing table to match requests like / api/order.
But the second requirement with a version number, the original Route definition of Controller is [Route ("/ api/v1/order"), but now it has to be upgraded to v2 and there are hundreds of interfaces, which requires a modification, which may be confused.
Now that there's a simpler and more elegant way to do this, you can uniformly add a global prefix routing tag. Let's take a look at it.
IApplicationModelConvention interface
First, we need to use the interface IApplicationModelConvention, which is under the Microsoft.AspNetCore.Mvc.ApplicationModels namespace. Let's take a look at the definition of the interface.
Public interface IApplicationModelConvention {void Apply (ApplicationModel application);}
We know that the MVC framework has some conventions, so this interface is mainly used to customize some MVC conventions, and we can add or modify some conventions by specifying ApplicationModel objects. You can see that the interface provides an Apply method, which has an ApplicationModel object, which we can use to modify what we need. The MVC framework itself injects this interface into Services when it starts, so we just need to implement this interface and configure it a little.
So let's take a look at what the ApplicationModel object has:
Public class ApplicationModel: IPropertyModel, IFilterModel, IApiExplorerModel {public ApiExplorerModel ApiExplorer {get; set;} public IList Controllers {get;} public IList Filters {get;} public IDictionary Properties {get;}}
You can see that there are attributes such as ApiExplorer,Controllers,Filters,Properties.
ApiExplorerModel: mainly configure some things about the default MVC ApiExplorer, including Api description information, group information, visibility and so on.
ControllerModel: it is mainly related to the Comtroller default convention. There are more things in this, so we will not introduce them one by one. We will configure one of the things in a moment.
IFilterMetadata: an empty interface, which mainly acts as a tag.
Another thing to tell you is that you can see that the Controllers property above is an IList, that is to say, all the Controller information in your program is recorded in this list. You can set it for a certain part or a certain Controller by traversing, including the Actions information in the Controller can be set in this way. We can use this feature to flexibly modify the MVC framework. Isn't it cool.
Next, we will use this feature to implement our theme for today. Thank you for your like ~:)
Add a global routing unified prefix
There's not so much nonsense, just go to the code, and all you have to say is in the code:
/ / define a class RouteConvention to implement IApplicationModelConvention interface public class RouteConvention: IApplicationModelConvention {private readonly AttributeRouteModel _ centralPrefix; public RouteConvention (IRouteTemplateProvider routeTemplateProvider) {_ centralPrefix = new AttributeRouteModel (routeTemplateProvider);} / / Apply method public void Apply (ApplicationModel application) {/ / traverse all Controller foreach (var controller in application.Controllers) {/ / Controller var matchedSelectors = controller.Selectors.Where (x = > x.AttributeRouteModel! = null). ToList () If (matchedSelectors.Any ()) {foreach (var selectorModel in matchedSelectors) {/ / add another routing prefix selectorModel.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel (_ centralPrefix, selectorModel.AttributeRouteModel) on the current route;}} / / Controller var unmatchedSelectors = controller.Selectors.Where without tagging RouteAttribute (x = > x.AttributeRouteModel = = null). ToList () If (unmatchedSelectors.Any ()) {foreach (var selectorModel in unmatchedSelectors) {/ / add a routing prefix selectorModel.AttributeRouteModel = _ centralPrefix;}
Then we can start using the class we defined ourselves.
Public static class MvcOptionsExtensions {public static void UseCentralRoutePrefix (this MvcOptions opts, IRouteTemplateProvider routeAttribute) {/ / add our custom RouteConvention opts.Conventions.Insert (0, new RouteConvention (routeAttribute)) to implement IApplicationModelConvention;}}
Finally, in the Startup.cs file, just add the extension method above.
Public class Startup {public Startup (IHostingEnvironment env) {/ /...} public void ConfigureServices (IServiceCollection services) {/ /. Services.AddMvc (opt = > {/ / routing parameters are still valid here, such as adding a version number opt.UseCentralRoutePrefix ("api/v {version}");} public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {/ /. App.UseMvc ();}}
Where opt.UseCentralRoutePrefix is the extension method defined above, where routing parameters can still be used, so for example, you can specify a version number for your interface. After that, all your Controller RoteAttribute will be prefixed with this prefix, which perfectly solves the need for the original version number. They look something like this:
[Route ("order")] public class OrderController: Controller {/ / routing address: / api/v {version} / order/details/ {id} [Route ("details/ {id}")] public string GetById (int id, int version) {/ / above can receive the version number, return version and id return $"other resource: {id}, version: {version}" }} public class ItemController: Controller {/ / routing address: / api/v {version} / item/ {id} [Route ("item/ {id}")] public string GetById (int id, int version) {/ / above can receive the version number, return version and id return $"item: {id}, version: {version}";}}
The above boldface, I hope you can understand and use, this example is only a very small scene in the actual requirements, there will be a variety of normal or abnormal requirements in a specific project, we have to think a lot when doing a function, in fact, there are many things to learn about the MVC framework, including its design ideas, expansibility and other things that need to be slowly understood.
On how to use ASP.NETCoreMVC to configure global routing prefixes to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
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.