问题描述
我需要一些帮助。
我正在使用 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>