【问题标题】:How to get an ID from url without using "?id=" in route config?如何在路由配置中不使用“?id =”从 url 获取 ID?
【发布时间】:2018-02-26 22:46:57
【问题描述】:

对此有很多问题,但没有一个可以澄清这个特定场景。

我想创建一个与控制器或动作名称无关的 URL,并且我希望将 ID 值直接放在那里(而不是 "?id=")。

意思是我想要以下网址:

http://localhost/word/43

在 ID 为“43”的控制器“nevermind”中调用“whatever”动作。

在路线配置中我有:

routes.MapRoute(
    name: "yes",
    url: "word/{id}",
    defaults: new { controller = "nevermind", action = "whatever"},
    constraints: new { id = @"\d+" }
);

如果我输入 URL localhost/word?id=43 它工作正常,如果我输入我想要的 URL,即 localhost/word/43,它不起作用,id 出现为 null。

控制器方法是

public ActionResult whatever(int id)
{
    ....
}

【问题讨论】:

  • 请更新您的帖子以包含whatever 操作的源代码。
  • 您需要显示控制器方法的签名 - 如果它的 public ActionResult whatever(int id),并且您的路由在默认路由(或任何其他匹配路由)之前,那么您的代码可以正常工作
  • @StephenMuecke 它必须与Request.Params 在一起,这就是他得到空值的原因。否则,他会得到一个例外。请参阅下面的答案。
  • @KobyDouek, Request.Params 与此无关。它是一个路由定义
  • @StephenMuecke 这正是我要说的......你读过我的回答吗?他使用了Request.Params,现在他正在使用路由,这就是他得到空值的原因。

标签: c# asp.net-mvc url routes config


【解决方案1】:

你可以使用属性

[Route("api/[controller]")]
public class YourController : Controller
{
    HttpPost("{id}")
    public IActionResult YorMethod(int id)
    {

    }
}

然后在您的请求中: http://localhost:5166/api/YourController/YorMethod/2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2010-11-02
    • 2014-04-15
    • 2021-03-25
    • 2012-06-17
    相关资源
    最近更新 更多