【问题标题】:Asp.net core 3.1 Replace Slash (/) by question Marq (?) in the UrlAsp.net core 3.1 用 URL 中的问题 Marq (?) 替换斜杠 (/)
【发布时间】:2020-10-07 14:24:55
【问题描述】:

我们要在 Asp.net core 3.1 中配置路由。

我们有一个 GetDepart 操作

[HttpGet("GetDepart/{id}")]
public async Task<ActionResult<Depart>> GetDepart(int id)
{
    //Return a Department
}

如何配置路由以将斜杠 (/) 替换为问号 (?) 在网址中,

因此,我们想要 http://localhost:44339/Departs/GetDepart ?id=1 而不是 http://localhost:44339/Departs/GetDepart/1

【问题讨论】:

  • 您将 / 替换为 ?例如使用string.Replace("/", "?"); 但这不是你在这里寻找的。也许这可以帮助:c-sharpcorner.com/UploadFile/ca2535/query-string-in-Asp-Net
  • @Jelle 该链接与此问题无关。
  • @PanagiotisKanavos 文章分为两部分,我应该直接发送第二部分:c-sharpcorner.com/UploadFile/1e050f/…
  • @Jelle 第一篇文章是关于 WebForms 的,除了孤立的 sn-ps 之外,并没有真正讨论查询字符串。其中大部分只是描述了创建一个包含几个字段的 WebForms 表单
  • @Jelle,问题是关于 Asp.net core web api 中的路由,我需要“?”在“/”的 URL 中,这需要在 HttpGet 动词中配置操作

标签: c# asp.net-mvc asp.net-core asp.net-web-api


【解决方案1】:

您可能正在寻找Sources

这样的事情应该能让你到达你想去的地方......

[HttpGet("GetDepart")]
public async Task<ActionResult<Depart>> GetDepart([FromQuery] int id)
{
    //Return a Department
}

注意id 参数上的[FromQuery] 属性。

【讨论】:

  • 我使用属性 [HttpGet("GetDepart/{id}")] 配置路由,但我必须在 URL 中加上斜杠 (/) 如何替换 [HttpGet("GetDepart/{ id}") 接收 "?"而不是“/”
【解决方案2】:

HttpGetAttribute 需要模板参数,但是模板不能包含'?'性格,是设计使然。 所以如果你想使用?id=1,你可以这样使用(但是这种方式和路由不同,当http://localhost:44339/Departs/GetDepart也可以去action):

[HttpGet("GetDepart")]

    public async Task<ActionResult<Depart>> GetDepart(int id)
    {
        //Return a Department
    }

int id前不需要添加[FromQuery],模型绑定默认会在查询字符串中找到,可以参考official document of model binding

【讨论】:

  • 同意,但在我看来,GetDepart/{id} 更适合写成路线
  • 谢谢,如果参数是模型,那么我必须使用 HttpGet 或者我必须将其更改为 HttpPost,因为模型无法在 url 中发送。
猜你喜欢
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-17
相关资源
最近更新 更多