ASP. NET CORE MVC implements a minus-delimited (Kebab case)-style URL

Source: Internet
Author: User

in ASP. NET CORE MVC, the default Route template is: /{controller}/{action} . We can turn the URL into lowercase by turning on the URL lowercase conversion, but the resulting URL is not friendly when the Controller or Action is a phrase. Assuming that we have the Usercontroller and AddUser methods, the URL generated by the framework might be: /user/adduser , which might be the result of the following when the lowercase conversion is turned on: /user/adduser . There is no problem with URLs that contain uppercase characters, but the lower-case URLs are more general, and the problem with fully converting lowercase is that the URLs are poorly readable. This article will provide some code to help the framework generate a minus-delimited-style URL, and when the code is applied, the resulting URL looks like this: /user/add-user . Microsoft has provided us with a routeattribute that can be tagged with a Controller or Action to achieve the purpose of a custom access path. This is a very powerful approach, but it's a bit cumbersome to use in larger projects. After all, manually tagging each Controller and Action has a small amount of work to do. An icontrollermodelconvention interface is defined in the ASP. NET CORE MVC framework, and we can implement this interface to attach a Route model to the Action at run time. Create a new Dashedroutingconvention class file in your project with the following code:

     Public classdashedroutingconvention:icontrollermodelconvention { Public voidApply (Controllermodel Controller) {varHasrouteattributes = controller. Selectors.any (selector =Selector. Attributeroutemodel!=NULL); if(hasrouteattributes) {//This controller manually defined some routes, so treat this//As an override and don't apply the convention here.                return; }            foreach(varControlleractioninchController. Actions) {foreach(varSelectorinchControllerAction.Selectors.Where (x = X.attributeroutemodel = =NULL))                {                    varParts =Newlist<string>(); foreach(varattrinchController. Attributes) {if(attr isAreaattribute area) {Parts. Add (area.                        RouteValue); }                    }                    if(parts. Count==0&& Controller. Controllername = ="Home"&& Controlleraction.actionname = ="Index"                    )                    {                        Continue; } parts. ADD (Pascaltokebabcase (Controller.                    Controllername)); if(Controlleraction.actionname! ="Index") {parts.                    ADD (Pascaltokebabcase (controlleraction.actionname)); } selector. Attributeroutemodel=NewAttributeroutemodel {Template=string. Join ("/", parts)}; }            }        }        Private Static stringPascaltokebabcase (stringvalue) {            if(string. IsNullOrEmpty (value)) {returnvalue; }            returnRegex.Replace (Value,"( ? <!^) ([A-z][a-z]| (? <=[A-Z]) [A-z])",                    "-$1", regexoptions.compiled). Trim ().        ToLower (); }    }

After that, the dashedroutingconvention is registered in the Startup.cs.

 Public void configureservices (iservicecollection services) {    //  ADD Framework services.    Services. ADDMVC (options = options. Conventions.add (new  dashedroutingconvention ()));}

At this point, all the code is complete. Notices:

    1. This code supports area and also escapes the area name.
    2. This code implements functionality using custom routing, so it may have an impact on predefined routes.
    3. More information related to routing can be found in: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing
    4. This code refers to other code, see: Https://stackoverflow.com/questions/40334515/automatically-generate-lowercase-dashed-routes-in-asp-net-core
    5. Yard Farm is busy. Authorization Center has been enabled this code, demo: https://passport.coderbusy.com/

ASP. NET CORE MVC implements a minus-delimited (Kebab case)-style URL

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.