asp.net Core MVC Configuration Global Routing prefix _ Practical tips

Source: Internet
Author: User
Tags static class

asp.net Core MVC configuration global route prefix

Objective

Hello everyone, today we introduce a new feature of ASP.net Core MVC, which adds a unified prefix to global routing. Strictly speaking, it is not a new feature, but it is unique to core MVC.

Application background

I do not know when you are doing Web API applications, have encountered this scenario, that is, all interfaces are started with/API, that is, our API interface request address is like this:

http://www.example.com/api/order/333

Or a demand like this.

http://www.example.com/api/v2/order/333

In the past, if we were to implement this requirement, we could add a feature routing attribute such as [Route ("/api/order") in Controller, and then the MVC framework would scan your routing table to match the request to/api/order.

But the second version of the requirement, originally Controller Route definition is [Route ("/api/v1/order")], now to upgrade to the V2, there are hundreds of interfaces, which requires a change, may be Meng.

Now, there is a much simpler and more elegant way to do this, and you can unify to add a global prefix route tag, let's take a look here.

Iapplicationmodelconvention interface

First, we need to use the interface to Iapplicationmodelconvention, which is located under the Microsoft.AspNetCore.Mvc.ApplicationModels namespace, and we'll look at the definition of the interface.

Public interface iapplicationmodelconvention
{
 void Apply (Applicationmodel application);
}
 

We know that there are some conventions in the MVC framework, and that this interface is primarily used to customize some of the MVC conventions that we can add or modify by specifying Applicationmodel objects. You can see that the interface provides a apply method, and this method has a Applicationmodel object that we can use to modify what we need, and the MVC framework itself injects this interface into Services at startup. So we just need to implement this interface, and then configure it slightly.

Then let's take a look at what applicationmodel this object has:

public class Applicationmodel:ipropertymodel, Ifiltermodel, Iapiexplorermodel
{public
 Apiexplorermodel apiexplorer {get; set;}
 Public ilist<controllermodel> controllers {get;}
 Public ilist<ifiltermetadata> Filters {get;}

 Public Idictionary<object, object> Properties {get;}
}

You can see attributes such as apiexplorer,controllers,filters,properties.

    1. Apiexplorermodel: The main thing is to configure the default MVC API Explorer, including the description information of the API, group information, visibility, and so on.
    2. Controllermodel: The main is comtroller default convention related, this inside things are more, not one of the introduction, we will configure a thing inside.
    3. Ifiltermetadata: null interface, mainly play the role of a marker.

One more place to tell you is that you can see the controllers property above it is a ilist<controllermodel>, which means that this list records all the Controller information in your program, You can set up a section or a Controller through traversal, including information about the actions in Controller, which can be set in this way, and we can use this feature to make it very flexible to transform the MVC framework, which is cool.

Below, we use this feature to implement our today's topic. Thank you for your order of praise:)

To add a global route unified prefix

Not so much nonsense, directly on the code, to say all in the code:

Defines a class routeconvention to implement the Iapplicationmodelconvention interface public class Routeconvention:iapplicationmodelconvention {p

 Rivate readonly Attributeroutemodel _centralprefix; Public routeconvention (Iroutetemplateprovider routetemplateprovider) {_centralprefix = new Attributeroutemodel (
 Routetemplateprovider); The Apply method of//interface public void apply (Applicationmodel application) {//Traverse all Controller foreach (Var Controller in app Lication. Controllers) {//Routeattribute Controller var matchedselectors = Controller has been marked. Selectors.where (x => x.attributeroutemodel!= null).
   ToList ();
     if (Matchedselectors.any ()) {foreach (var selectormodel in matchedselectors) {//Add a route prefix to the current route) Selectormodel.attributeroutemodel = Attributeroutemodel.combineattributeroutemodel (_centralPrefix, SelectorModel.
    Attributeroutemodel); }///Controller var unmatchedselectors = Controller without marked Routeattribute. Selectors.where (x => X.attributeroUtemodel = = null).
   ToList (); if (Unmatchedselectors.any ()) {foreach (var selectormodel in unmatchedselectors) {//Add a route prefix Sele
    Ctormodel.attributeroutemodel = _centralprefix;

 }
   }
  }
 }
}

Then we can start using this class that we have defined ourselves.

public static class Mvcoptionsextensions
{public
 static void Usecentralrouteprefix (this mvcoptions opts, Iroutetemplateprovider Routeattribute)
 {
  //Add our Custom implementation iapplicationmodelconvention Routeconvention
  OPTs. Conventions.insert (0, New Routeconvention (Routeattribute));
 }

Finally, in the Startup.cs file, you can 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 (New Routeattribute ("Api/v{version}"))

 ;} public void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory)
 {
  // ...
  
  App. Usemvc ();
 }


of which, opt. Usecentralrouteprefix is the extension method defined above, where routing parameters are still available, so for example you can specify a version number for your interface and things like that. After that, all of your Controller Roteattribute will add this prefix, which will be the perfect solution for the initial version number. They might look 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 which can receive the version number, return version and ID returns
  $ "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 version number, return version and ID back
  $ "item: {ID}, version: {version}";
 }
}

Summarize

I hope you can understand and use the bold words above, this example is only a small scene in the actual demand, in the specific project will have a variety of normal or abnormal requirements, we do a function of a lot of thinking, in fact, the MVC framework there are many things to learn, including its design ideas, extensibility, and so on, are all things that need to be understood slowly. If you are interested in asp.net Core, you can pay attention to me, I will regularly share some of my learning achievements in the blog.

Through this article hope to help you, thank you for your support to this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.