ASP. NET Core MVC configuration global route prefix

Source: Internet
Author: User

Reference page:

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-setup-entityframework.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-dbcontext.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-razor-layout.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-view-start.html

Http://www.yuanjiaocheng.net/ASPNET-CORE/core-import-view.html

Objective

Hello everyone, today we present a new feature of ASP. NET Core MVC, which adds a uniform prefix to the global route. Strictly speaking is not a new feature, but a core MVC unique.

Application background

Do not know when you do the Web API application, have encountered this scenario, that is, all the interfaces are beginning with/API, that is, our API interface request address is like this:

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

Or is that the demand

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

In the past, if we were to implement this requirement, we could add one [Route("/api/order")] of these features to the Controller to Route Attribute, and then the MVC framework would scan your routing table to match /api/order that request.
But the second with the version number of the requirements, the original Controller's Route definition is [Route("/api/v1/order")] , now to upgrade to V2, and hundreds of interfaces, which requires a modification, may be confused.

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

Iapplicationmodelconvention interface

First, we need to use IApplicationModelConvention this interface, located Microsoft.AspNetCore.Mvc.ApplicationModels under the namespace, and let's look at the definition of the interface.

public interface IApplicationModelConvention{    void Apply(ApplicationModel application);}    

We know that the MVC framework has some conventions in it, so this interface is primarily about something that defines some MVC conventions that we can ApplicationModel add or modify by specifying objects. You can see that the interface provides a Apply method that has an ApplicationModel object that we can use to modify what we need, and the MVC framework itself injects this interface into the Services when it is started, so we just need to implement this interface and then configure it a little bit.

So let's see ApplicationModel what 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 that there are ApiExplorer ,, Controllers , and Filters Properties so on properties.

    • Apiexplorermodel: The main thing is to configure the default MVC API Explorer, including the API description information, group information, visibility, etc.
    • Controllermodel: The main comtroller is the default convention related, this inside things are more, do not introduce each, we will have to configure the inside of a thing.
    • Ifiltermetadata: An empty interface, which acts primarily as a marker.

There is one more place to tell you that you can see the Controllers property above it is one, that is, IList<ControllerModel> the list of all Controller information in your program, you can traverse the way for a certain part or a The controller is set up, including the actions in the controller can be set in this way, we can use this feature to very flexible to the MVC framework of the transformation, is not cool.

Let's use this feature to achieve our theme today. Thank you for your order of praise ~:)

Add Global route Unified prefix

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

Define a class routeconvention to implement the Iapplicationmodelconvention interface public class routeconvention:iapplicationmodelconvention{    Private ReadOnly Attributeroutemodel _centralprefix; Public routeconvention (Iroutetemplateprovider routetemplateprovider) {_centralprefix = new Attributeroutemodel (    Routetemplateprovider); }//The Apply method of the interface public void apply (Applicationmodel application) {//Traverse all Controller foreach (Var co Ntroller in Application. Controllers) {//controller var matchedselectors = Controller with Routeattribute already marked. Selectors.where (x = X.attributeroutemodel = null).            ToList ();                    if (Matchedselectors.any ()) {foreach (var selectormodel in matchedselectors) { Add one more route prefix on the current route Selectormodel.attributeroutemodel = Attributeroutemodel.combin Eattributeroutemodel (_centralprefix, Selectormodel.attributeroutemodel);                }}//Controller var unmatchedselectors = Controlle without tag Routeattribute R.selectors.where (x = X.attributeroutemodel = = null).            ToList ();                if (Unmatchedselectors.any ()) {foreach (var selectormodel in unmatchedselectors)                {//Add a route prefix Selectormodel.attributeroutemodel = _centralprefix; }            }        }    }}

Then we can start using this class of our own definition.

public static class MvcOptionsExtensions{    public static void UseCentralRoutePrefix(this MvcOptions opts, IRouteTemplateProvider routeAttribute)    {        // 添加我们自定义 实现IApplicationModelConvention的RouteConvention        opts.Conventions.Insert(0, new RouteConvention(routeAttribute));    }}

Finally, in the Startup.cs file, add the extension method above.

public class Startup{    public Startup(IHostingEnvironment env)    {        //...    }    public void ConfigureServices(IServiceCollection services)    {        //...                services.AddMvc(opt =>        {            // 路由参数在此处仍然是有效的,比如添加一个版本号            opt.UseCentralRoutePrefix(new RouteAttribute("api/v{version}"));        });    }    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)    {        //...                app.UseMvc();    }}

Which opt.UseCentralRoutePrefix is the extension method defined above, where the routing parameters are still available, so for example you can assign a version number to your interface. After that, all of your Controller's roteattribute will be added with this prefix, which perfectly solves the need for the first version number. They seem to be like this:

[Route("order")]public class OrderController : Controller{    // 路由地址 : /api/v{version}/order/details/{id}    [Route("details/{id}")]    public string GetById(int id, int version)    {        //上面是可以接收到版本号的,返回 version 和 id        return $"other resource: {id}, version: {version}";    }}public class ItemController : Controller{    // 路由地址: /api/v{version}/item/{id}    [Route("item/{id}")]    public string GetById(int id, int version)    {        //上面是可以接收到版本号的,返回 version 和 id        return $"item: {id}, version: {version}";    }}
Summarize

Above the bold words, I hope you can understand and use, this example is only a small real needs of a scene, in the specific project will have a variety of normal or non-normal needs, we do a function of the time to think more, in fact, the MVC framework has a lot of things to learn, including its design ideas, Extensibility is something that needs to be understood slowly. If you are interested in ASP, you can pay attention to me, I will regularly share some of my study results in the blog.

Thanks for your support, if you think this article is helpful to you, thank you for your "recommendation", Good night.

This address: http://www.cnblogs.com/savorboard/p/dontnet-IApplicationModelConvention.html
Author Blog: Savorboard
Welcome reprint, please give the source and link in obvious position

ASP. NET Core MVC configuration global route prefix

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.