HTTP 错误 405 | ASP.NET Core 3.1 MVC |斜线问题

问题描述

我需要一些帮助。

我正在使用 ASP.NET Core 3.1 MVC,一切顺利,但不适用于特定操作。

我有几个页面:开始 -> 索引 -> 添加用户

多亏了 <button>,我才能在我的页面之间导航。

Index.cshtml

<form asp-controller="Home" asp-action="AddUser" asp-route-GB="@ViewBag.GB">
      <button type="submit" class="btn btn-success">Add</button>
</form>

HomeController.cs

[HttpGet]
public ActionResult Start(string GB) {
  if (string.IsNullOrEmpty(GB)) {
    return RedirectPermanent("Error");
  }
  else {
    return View();
  }
}
[HttpGet]
public ActionResult Index(string GB) {
  if (string.IsNullOrEmpty(GB)) {
    return RedirectPermanent("Error");
  }
  else {
    return View();
  }
}
[HttpGet]
public ActionResult AddUser(string GB) {
  if (string.IsNullOrEmpty(GB)) {
    return RedirectPermanent("Error");
  }
  else {
    return View();
  }
}
public ActionResult Error() {
  return View();
}

网址结果:

https://localhost:XXXXX/Home/Start?GB=1 -> 进展顺利。

https://localhost:XXXXX/Home/Index?GB=1 -> 进展顺利。

https://localhost:XXXXX/Home/AddUser?GB=1 -> HTTP 错误 405

但是!如果我在最后一个添加斜杠: https://localhost:XXXXX/Home/AddUser/?GB=1 -> 进展顺利。

这是怎么回事?我不想在浏览器上添加斜杠以使其正常工作...

解决方法

添加或创建api时的第一件事,它必须是POST类型而不是GET。 尝试使用 [HttpPost] 属性。它可能会解决您的问题。

,

好的,我明白了,基本上

  • <a> 支持 [HttpGet]
  • <button> + <form> 支持 [HttpPost]

如果您想使用 [HttpGet] 则:

<a class="btn btn-success" asp-controller="Home" asp-action="AddUser" asp-route-GB="@ViewBag.GB">
    Next Step
</a>

如果您想使用 [HttpPost] 则:

<form asp-controller="Home" asp-action="AddUser" asp-route-GB="@ViewBag.GB">
    <button type="submit" class="btn btn-success">Next Step</button>
</form>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...