当前位置:网站首页>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
边栏推荐
- Get the column name list of the table quickly in Oracle
- 面试百分百问到的进程,你究竟了解多少
- 【解决报错】Error in v-on handler: “TypeError: Cannot read property ‘resetFields’ of undefined”
- feign报400处理
- 【WPF绑定3】 ListView基础绑定和数据模板绑定
- Smart doc + Torna generate interface document
- CentOS MySQL multi instance deployment
- The new MySQL table has a self increasing ID of 20 bits. The reason is
- Linux MySQL data timing dump
- [markdown notes]
猜你喜欢

Idea of batch manufacturing test data, with source code

Rtklib 2.4.3 source code Notes

Detailed explanation of Milvus 2.0 quality assurance system

线性代数感悟之2

Installing labellmg tutorial in Windows

Detailed explanation of Niuke - Gloves

Get the column name list of the table quickly in Oracle

ByteVCharts可视化图表库,你想要的我都有

Mock test

VLAN高级技术,VLAN聚合,超级Super VLAN ,Sub VLAN
随机推荐
1-3 nodejs installation list configuration and project environment
Calculation formula related to tolerance analysis
Introduction to new functions of camtasia2022 software
Document operation II (5000 word summary)
. net type transfer
Pseudo Distributed installation spark
TypeError: set_ figure_ params() got an unexpected keyword argument ‘figsize‘
Rtklib 2.4.3 source code Notes
[pimf] openharmony paper Club - what is the experience of wandering in ACM survey
蓝桥杯省一之路06——第十二届省赛真题第二场
[PROJECT] small hat takeout (8)
拷贝构造函数 浅拷贝与深拷贝
Error in v-on handler: "typeerror: cannot read property 'resetfields' of undefined"
Nifi fast installation and file synchronization
BUG_ me
Kingdee Cloud Star API calling practice
1-5 nodejs commonjs specification
Getting started with JDBC
ACL 2022 | DialogVED:用于对话回复生成的预训练隐变量编码-解码模型
JS, entries(), keys(), values(), some(), object Assign() traversal array usage