当前位置:网站首页>Detailed explanation of C webpai route

Detailed explanation of C webpai route

2022-04-23 17:04:00 begeneral

About MVC The routing , I'm sure you're all familiar . Our common route is :{controller}/{action}/{id}, This default route can meet our daily needs , Because this route is very simple , So there is no introduction here , Today we will focus on Route and RoutePrefix These two routing features

Go straight to the code :

[RoutePrefix("values")]
    public class ValuesController : ApiController
    {
        [HttpGet]
        [Route("GetID")]
        public int GetID()
        {
            return 50;
        }

        //[HttpGet]
        //[Route("AbcAge")]
        //public int GetAge()
        //{
        //    return 100;
        //}
    }

What we use here is webapi To test the controller , So we put webapi Post your routing configuration code :

config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }             
            );

This is a webapi Default routing configuration , Notice here the first line of code :config.MapHttpAttributeRoutes(); The function of this line of code is to turn on attribute routing , That's what we're going to introduce now Route and RoutePrefix. Without this line of code , Attribute routing doesn't work .

Next, run the program , Enter... In the address bar of the browser :/values/getid, Found that the program returned 50;

I don't know if you have found out , above url It does not match the default routing configuration , In other words, this route is not converted to... Through the default route url Of , But through RoutePrefix and Route These two feature classes are used to convert . Let's see RoutePrefix Definition of property class :

You can see that this feature class can only be used for class , To match the controller . Look again. Route The definition of a class :

This feature class can be used on classes , It can also be used in methods . Let's take a closer look at the use of these two feature classes

Just now we said url Is converted through these two classes , To prove the point , We comment out the default routing configuration , Then run the program again , It is found that the program can still return normally . You can test this by yourself , But don't put config.MapHttpAttributeRoutes(); This line of code comments out , Otherwise it will prompt 404

Now let's put RoutePrefix Change the parameters of , To such :[RoutePrefix("myvalues")], Run the program , Type in the browser :/myvalues/getid, It is found that the program can still return normally . This shows that this class can also customize the name of the controller .

Here we are. , I find webapi The default routing configuration is not reasonable ,webapi The default routing configuration is :api/{controller}/{id}, There is no method specified here. This fragment variable . So when we follow mvc The way to call webapi Method time , Because of the lack of action, So can't call . So we are webapi Add a routing configuration to the routing configuration of , The added routing configuration is as follows :

config.Routes.MapHttpRoute(
                name: "MyApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

And then we put RoutePrefix and Route Are commented out , Run the program , Input :/api/values/getid, The program can return normally . Here is a problem to pay attention to , belt action The routing template must be placed on top of the default template , Otherwise, the routing system will still choose the default template .

Let's prove it RoutePrefix、Route Relationship with routing template :1、 When the route matches , Only one of them can be selected for matching , The two cannot be used together ; When using RoutePrefix When labeling the controller , You have to use Route Annotation method ;2、 It can also be used alone Route Configure routing for the method .

Let's prove the first point first , The test code is as follows :

[RoutePrefix("api/values")]
    public class ValuesController : ApiController
    {
        [HttpGet]
        //[Route("GetID")]
        public int GetID()
        {
            return 50;
        }

        [HttpGet]
        //[Route("AbcAge")]
        public int GetAge()
        {
            return 100;
        }
    }
config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "MyApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

Input /api/values/getid, The return result is shown in the figure :

Because we annotated it out Route, And this controller has 2 individual get Method , All will prompt this error . If we put getage Methodical [HttpGet] The correct result can be obtained by removing the annotation attribute .

This result shows that the routing system uses attribute routing generation url, Because if a routing template is used to generate url You can get the right result , Because we have added... In the routing template action, and RoutePrefix Is not specified action, When requested /api/values/getid when , The routing system will select one by default httpget Method , If there is 2 individual httpget The method will report the above error .

Let's see how to use it alone Route To route the method

hold RoutePrefix And routing templates are all commented out ,getid Methodical Route Set to :[Route("api/values/GetID")], Input /api/values/getid, You can return the correct result . And then put this Route Set to [Route("GetID")], Input /getid, You can also return the correct result .

This shows that we can use Route Set a routing template for a function separately , This routing template is only applicable to this function .

版权声明
本文为[begeneral]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230554082141.html