ASP.NET Core:从GET重定向到POST

Xav*_*eña 0 c# asp.net asp.net-core

我想这样叫MarriageByIdGET:

var url = '/MarriageById?id=' + id;
Run Code Online (Sandbox Code Playgroud)

但我也想拥有一个ActionResult Marriage(Marriage marriage)可以在显示视图之前进行一些处理的单元。第二个原因必须是POST因为它还将收到来自asp的“发送表单”。

我正在尝试此解决方案(请参见下面的我自己的实现),但仍将其作为GET重定向,ActionResult Marriage但未找到:

[HttpGet]
public ActionResult MarriageById(int id)
{
    var marriage = _marriageRepository.GetById(id);
    return RedirectToAction(nameof(Marriage), marriage);
}

[HttpPost]
public ActionResult Marriage(Marriage marriage)
{
    var people = _personRepository.GetAll();

    ViewBag.men = Utils.GetPersonsSelectListByGender(people, isMale: true);
    ViewBag.women = Utils.GetPersonsSelectListByGender(people, isMale: false);

    return View(marriage);
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*r B 6

使用Always RedirectToAction总是意味着GET,因此这无法达到Marriage仅接受POST 的action方法。

但是,您自己调用其他方法没有任何问题,它仍然是与其他方法一样的方法。因此,请尝试以下操作:

return Marriage(marriage);
Run Code Online (Sandbox Code Playgroud)

另外,请注意:如果该Marriage方法始终仅用于显示数据,而从不保存,存储或更改数据,那么使用POST并不是最佳选择。POST通常暗含带有副作用(保存,存储,更改甚至删除)的调用,通常最好遵循该约定。