路由以允许来自查询字符串和默认{id}模板的参数

编程入门 行业动态 更新时间:2024-10-27 16:28:45
本文介绍了路由以允许来自查询字符串和默认{id}模板的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在ASP.Net Core WebAPI Controller中有一个操作,该操作带有一个参数.我正在尝试将其配置为能够以以下形式调用它:

I have an action in my ASP.Net Core WebAPI Controller which takes one parameter. I'm trying to configure it to be able to call it in following forms:

api/{controller}/{action}/{id} api/{controller}/{action}?id={id}

我似乎无法正确地进行路由,因为我只能识别一种形式. (简化的)动作签名如下所示:public ActionResult<string> Get(Guid id).这些是我尝试过的路线:

I can't seem to get the routing right, as I can only make one form to be recognized. The (simplified) action signature looks like this: public ActionResult<string> Get(Guid id). These are the routes I've tried:

  • [HttpGet("Get")]-映射到api/MyController/Get?id=...
  • [HttpGet("Get/{id}")]-映射到api/MyController/Get/...
  • 它们都
  • 都映射到api/MyController/Get/...
  • [HttpGet("Get")] -- mapped to api/MyController/Get?id=...
  • [HttpGet("Get/{id}")] -- mapped to api/MyController/Get/...
  • both of them -- mapped to api/MyController/Get/...

如何配置要使用这两种URL形式调用的操作?

How can I configure my action to be called using both URL forms?

推荐答案

如果要使用路由模板 您可以在Startup.cs这样的配置方法中提供一个:

if you want to use route templates you can provide one in Startup.cs Configure Method Like This:

app.UseMvc(o => { o.MapRoute("main", "{controller}/{action}/{id?}"); });

现在您可以使用两个请求地址.

now you can use both of request addresses.

如果要使用属性路由,可以使用相同的方法:

If you want to use the attribute routing you can use the same way:

[HttpGet("Get/{id?}")] public async ValueTask<IActionResult> Get( Guid id) { return Ok(id); }

更多推荐

路由以允许来自查询字符串和默认{id}模板的参数

本文发布于:2023-11-13 01:19:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583012.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   字符串   模板   参数   id

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!