.net core WebApi 带属性路由([HttpGet("{id}", Name = "Get")])

6 篇文章 0 订阅
3 篇文章 0 订阅
  1. WebApi 带属性路由介绍 参见:WebApi路由机制详解
    内容详实,举例简单易懂。

  2. 但是该文中没有对带属性路由的另一种方式做详细介绍,即在HttpGet、HttpPut、HttpPost、HttpDelete 这些标签中添加属性。以下以[HttpGet("{id}", Name = “Get”)] 为例

  3. 在Controller中定义属性路由
    [


```csharp
Route("api/[controller]")]
public class UserManageController : Controller
    {
        // GET: api/UserManager
        [HttpGet]
        public IActionResult GetUserInfoAll()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/UserManager/5
        [HttpGet("{id}", Name = "GetTest")]
        [ActionName("Get1")]
        public string Get()
        {
            return "value";
        }
   }

(1)使用 http://localhost:5000/api/userManage 请求,返回

value1, 
value2

属性路由中没有定义action,同时存在多条Get方法,但是第二条Get方法中带有了特定路由属性,因此匹配时自动排除,默认匹配到GetUserInfoAll方法。

(2)使用 http://localhost:5000/api/userManage/GetUseInfoAll 请求,返回

value

由于属性路由中没有定义action,使用URl访问时,此时“GetUseInfoAll ”匹配的是“{id}”,即路由规则为"api/[controller]/{id}" 如果将id强制定义为整数则不会返回值,无法访问。
(3)[HttpGet("{id}", Name = “Get”)] 中的Name值,目前测试可以用于寻址,其它作用不明
string uri = Url.Link(“GetTest2”, id = 1);
返回http://localhost:5000/Get1/1

  1. 总结:[HttpGet("{id}", Name = “Get”)] 等同于于Route中带属性,其中的属性值可以相互参考
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue 3.0 和 ASP.NET Core WebAPI 都支持动态路由,实现起来也比较简单。 首先,在 ASP.NET Core WebAPI 中,我们需要在 Startup.cs 中配置路由。可以使用以下代码: ``` app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action}/{id?}"); }); ``` 这个配置会将请求转发到对应的控制器和方法中。其中,{controller} 和 {action} 表示控制器和方法名,{id?} 表示可选参数。 接着,在 Vue 3.0 中,我们可以使用 vue-router 实现动态路由。可以使用以下代码: ``` const router = createRouter({ history: createWebHistory(), routes: [ { path: '/:controller/:action/:id?', name: 'dynamic', component: DynamicComponent } ] }) ``` 这个配置会将请求转发到 DynamicComponent 组件中。其中,:controller、:action 和 :id? 表示控制器、方法名和可选参数。 最后,我们可以在 DynamicComponent 组件中调用 ASP.NET Core WebAPI 中的动态路由。可以使用以下代码: ``` axios.get(`/api/${this.$route.params.controller}/${this.$route.params.action}/${this.$route.params.id}`) .then(response => { // 处理响应 }) .catch(error => { // 处理错误 }) ``` 这个代码会发送请求到对应的控制器和方法中,其中,this.$route.params.controller、this.$route.params.action 和 this.$route.params.id 分别对应控制器、方法名和参数。 以上就是 Vue 3.0 和 ASP.NET Core WebAPI 实现动态路由的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值