How "ASP. NET Core" is useful for naming routing rules

Source: Internet
Author: User

In the old week to the partners to introduce the custom view search path method, this article let's talk about the URL path rule name problem. Before you talk about today's topic, let's add some stuff. Three ordered parameters were used to set the view search path in the previous article: {2}{1}{0}, respectively area, Controller, Action. Several special views are mentioned, such as _layout.cshtml, _viewstart.cshtml and so on. The _layout.cshtml page is placed by default in the/views/shared directory, but _viewstart.cshtml and _viewimports.cshtml should not be placed in the Shared directory, generally should be placed under the/views, This allows them to be used for all views. If they are placed in a shared directory, they only work on views in the shared directory, but not on other views under view.

For example, put it under the/views.

Views (catalogue)    │  _viewimports.cshtml    │  _viewstart.cshtml    │      └─home (directory, controller's name)            Index.cshtml (view, Action)

Where Home is a subdirectory, corresponding to the index.cshtml view in the controller home,home corresponds to the Action name Index. At this point, the content in _viewstart and _viewimports is applied to all views under/views, such as index.cshtml.

If you change to this.

Views    ├─home    │      about.cshtml    │      index.cshtml    │      _viewimports.cshtml    │      _ viewstart.cshtml    │          └─users            addnew.cshtml

At this point, the views have two subdirectories, home is a controller, the users is another controller, at this time, _viewstart and _viewimports only for the view below the Home function, the view under the Users directory is not working.

The main purpose of _viewstart is to execute before all view files are executed, and we typically use it to set the Layout property to specify the layouts page (equivalent to the page master) used, so that we do not need to add layout = "xxxx" to each view. _viewimports is primarily used to introduce namespaces that are used in C #, so you don't need to write a bunch of @using Razor tags in each view.

These two files are agreed, so you should not casually change its name, _viewimports can be Razortemplateengineoptions class Importsfilename properties to modify, but, _viewstart seems unable to change, Old weeks to see ASP. NET core source code is dead, it is estimated that the file name can not be changed.

In fact, these two files should not be renamed, and you changed the name is not much use, anyway, the function is unchanged, or to abide by the Convention better, so that others see your project also understand. _layout.cshtml file if not necessary, you should not change the name, if your application to use multiple layout views, may build subdirectories, and then each sub-directory _layout, so the structure is clear, after all, see _layout.cshtml know it is the motherboard page.

Rule templates

As we all know, in the Startup.configure method, the URL path rule is specified in this way.

            App. Usemvc (route =            {                route). MapRoute ("main""{controller=students}/{action=list}/{sid?} " );                Route. MapRoute ("edit_post""{controller}-{action}" );            });

You can add a K rule, like the above example, and I added two rules.

{Controller} and {action} are the names of the conventions used to identify the controller and action, so don't be clever, you need to write dead arguments for URL analysis, otherwise, you give a URL http://dog.org/shop PING/PAY/500, the application doesn't know which paragraph represents the Controller, which is the action.

If both the controller and the action values are determined, then the other parameters are well analyzed.

Other parameters, if optional, can be appended with a question mark, such as {Controller}/{action}/{id?}, which indicates that the value of the ID is optional.

The above old week added two rules, edit_post that actually is not very standard, the URL paragraph best use "/" to separate, because "-" sometimes is not allowed, for example, the ID parameter can not be used before, you can not write {Controller}-{action}-{id?}, What if the ID contains the character "-"? and the "/" is different, the URL Encode will not pop this character.

So use/best, here-just the old week deliberately used for demonstration, URL, no need to play tricks, meaningless.

URL route specified based on Attribute

The URL route specified in the Startup.configure method is for the entire application, and if you want to specify the routing rules for individual controllers or individual actions, consider using the Attribute form.

The routing rules in the attribute form are similar to the application-level rules, except that when the level is applied, the parameter names (such as {controller}) are wrapped in curly braces, whereas in the attribute scenario, the brackets are used, it can only use two values: [Controller], [ Action]. Other parameters are also in curly braces. For example, [Controlloer]/[action]/[id] will error, you have to change [Controller]/[action]/{id?}.

The Routeattribute can be used either for the Controller type or for a single Action method. Let me give you an example, like this.

    [Route ("hello/[controller]/[action]")]      Public class Somethingcontroller:controller    {        [Route ("{name}} " )]        public iactionresult sayhi (string  name)        {            ...        }    } 

You can use such a url:http://localhost:999/hello/something/sayhi in a Attribute that is applied on a class. On the Sayhi method, the Route Attribute is used, specifying an additional parameter name, which is optional. It can then merge with the Route attribute on the class and become: Http://localhost:999/hello/something/sayhi/Peter. At this point, the string Peter is passed to the name parameter of the Sayhi method because the parameter name is the same as the parameter name in the Route, called name. If the parameter name in Sayhi is not called name, then you have to use Fromrouteattribute. Just like this.

        [Route ("{name?} " )]        public iactionresult sayhi ([Fromroute (name ="name") )] (string who )        {            ...        }

If you want the URL to give name a value in the int type, you can also limit it.

[Route ("{name:int}")]

In fact, these constraints correspond to the types below the Microsoft.AspNetCore.Routing.Constraints namespace.

Route Data

The route data is actually a dictionary that stores the key-value pairs of parameters and values in the URL path rule. This is very simple, I give an example, you will understand.

Let's use the example above directly.

 [Route  '  hello/[controller]/[action]   )]   class   Somethingcontroller: Controller {[Route (  {name?}   "   name   ")]string   who) { return   Json (routedata.values); } }

In the Sayhi method, we return the route data.

After running the application, enter the address: Http://localhost/hello/something/sayhi/Tom, the resulting output is as follows:

I don't have to explain it.

Give the route a name

The above is all F, this section is the subject of this article. Let's look back at the route that we've been looking at for example in the old week.

            App. Usemvc (route =            {                route). MapRoute ("main""{controller=students}/{action=list}/{sid?} " );                Route. MapRoute ("edit_post""{controller}-{action}" );            });

Each routing rule will have its own name, why should it be named? The most straightforward reason is to uniquely identify each rule. In addition to this factor, we can choose which rule to use in the development process, with the name, want to find out a rule is good, like when you go to school, the teacher named, either the name, or the number of students.

Attribute-based routing rules can also be named, for example.

[Route ("hello/[controller]/[action]" "prv")]

So it's named Prv, and you can write it that way.

  [Route ("hello/[controller]/[action]"Name ="[controller]_[ Action]")

This can also generate a unique name, such as Something_sayhi, with the name of the Controller and Action. But this method is too dynamic, it seems not so good control, or with a fixed name better.

To choose to use the specified URL route at development time, you need to add tag helper to the Razor page, and the markup helper class can extend some of the functionality of the HTML markup. Use the Tag helper page, or unify the instructions in the _viewimports.cshtml page.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The format is this:

< type full path;, < assembly >

The type is written in front (including the namespace name), and the assembly name is written behind, separated by commas. The asterisk (*) here is the best, it is a wildcard character, which means that all tag helper types are introduced. This is quick, a line of code.

And then in the HTML you write like this.

    <formMethod= "POST" asp-route= "Edit_post">         <Divclass= "Form-group">            <labelasp-for= "Name"></label>            <inputasp-for= "Name"class= "Form-control"/>            <spanasp-validation-for= "Name"class= "Text-danger"></span>        </Div>        <Divclass= "Form-group">            <labelasp-for= "Age"></label>            <inputasp-for= "Age"class= "Form-control"/>            <spanasp-validation-for= "Age"class= "Text-danger"></span>        </Div>        <inputasp-for= "ID"/>        <Buttontype= "Submit"class= "Btn Btn-dark">Submit</Button>    </form>

Other code you don't have to look, just look at this sentence is enough:

Asp-route= "Edit_post"

It means to use the rule that I just defined.

Route. MapRoute ("edit_post""{controller}-{action}");

As a result, such HTML is generated after it is run.

   <method= "POST"   action= "/students-editdata"   >        <class= "Form-group">             1650 words omitted here </form>          

Because I define the rule is {controller}-{action} form, so, controller is students,action is editdata, connect up is students-editdata.

So, why does it recognize the Controller and action values here, and you can see my code.

     Public classStudentscontroller:controller {ReadOnlyStudentdbcontext M_context; //Receive Dependency Injection         PublicStudentscontroller (Studentdbcontext c) {M_context=C; }         PublicIactionresult List () {varQ = fromSinchM_context. Students bys.idSelects; returnView (Q.tolist ()); }        /***************************************************/        //The following methods are used to edit the page[HttpGet] PublicIactionresult EditData ([Fromroute (Name ="Sid")]intID) {varQ = fromSinchM_context. Studentswhereid = =s.idSelects; Student Stu=Q.firstordefault (); if(Stu = =NULL)            {                returnContent ("This student could not be found on Earth. "); }            returnView (STU); } [HttpPost] PublicIactionresult EditData (Student s) {if(Modelstate.isvalid = =false)            {                returnView (s); } m_context.            Students.update (s); M_context.            SaveChanges (); returnredirecttoaction (nameof (List)); }    }

I defined the overloads of the EditData method, one for the GET request, one for the post request, and the form to post, so it can automatically recognize the controller and action name.

In case, if it is not the same name, good. You use asp-route-<value> to specify the values for each parameter. Like this.

    <method= "POST"          asp-route= "Edit_post"           Asp-route-controller= "Demo"          asp-route-action= "Runwork"           Asp-route-sid= "1">

Follow the name of the routing rule parameter directly behind the asp-route-.

One thing to note, Asp-route and Asp-controller, Asp-action is a conflict, if you use these two tags, you can not use Asp-route tag, of course, asp-route-xxx is available.

Well, today's content is going to be here, and by the way, the code for the example is also passed in to entertain the partners.

Sample source Code

How "ASP. NET Core" is useful for naming routing rules

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.