当前位置:网站首页>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
边栏推荐
- 【解决报错】Error in v-on handler: “TypeError: Cannot read property ‘resetFields’ of undefined”
- ◰ GL shadow map core steps
- EF core in ASP Generate core priority database based on net entity model
- ASP. Net core reads the configuration file in the class library project
- Log4j output log information to file
- Zhongang Mining: Fluorite Flotation Process
- Change the password after installing MySQL in Linux
- Net standard
- Regular filtering of Intranet addresses and segments
- About stream flow, write it down briefly------
猜你喜欢
Do you really understand the principle of code scanning login?
vscode如何比较两个文件的异同
Idea of batch manufacturing test data, with source code
【WPF绑定3】 ListView基础绑定和数据模板绑定
EF core in ASP Generate core priority database based on net entity model
VLAN advanced technology, VLAN aggregation, super VLAN, sub VLAN
Customize my_ Strcpy and library strcpy [analog implementation of string related functions]
Rtklib 2.4.3 source code Notes
自定义my_strcpy与库strcpy【模拟实现字符串相关函数】
Scope and scope chain in JS
随机推荐
VsCode-Go
Derivation of Σ GL perspective projection matrix
True math problems in 1959 college entrance examination
1-4 configuration executable script of nodejs installation
ACL 2022 | dialogved: a pre trained implicit variable encoding decoding model for dialogue reply generation
Baidu Map 3D rotation and tilt angle adjustment
Promise (III)
杂文 谈谈古典的《拆掉思维里的墙》
oracle 中快速获取表的列名列表
自定义my_strcpy与库strcpy【模拟实现字符串相关函数】
Document operation II (5000 word summary)
First knowledge of go language
手写事件发布订阅框架
ACL 2022 | DialogVED:用于对话回复生成的预训练隐变量编码-解码模型
1-2 characteristics of nodejs
Feign report 400 processing
JS to find the character that appears three times in the string
Introduction to new functions of camtasia2022 software
Promise (IV)
Milvus 2.0 质量保障系统详解