ASP.NET Core:从GET重定向到POST [英] ASP.NET Core: redirect from GET to POST

查看:291
本文介绍了ASP.NET Core:从GET重定向到POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以GET方式调用MarriageById,如下所示:

I want to call MarriageById as GET, like this:

var url = '/MarriageById?id=' + id;

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

But I also want to have a single ActionResult Marriage(Marriage marriage) that does some processing before showing the view. This second one must be POST because it will also receive the "send form" from asp.

我正在尝试此解决方案(请参阅下面的我自己的实现),但仍以GET和<找不到c3>:

I am trying this solution (see my own implementation below), but it is still redirected as a GET and ActionResult Marriage is not found:

[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);
}

推荐答案

使用RedirectToAction始终表示GET,因此无法达到仅接受POST的Marriage操作方法.

Using RedirectToAction always implies a GET, so this won't work to reach the Marriage action method that only accepts POST.

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

However there is nothing wrong with calling the other method yourself, it is still a method like any other. So try this instead:

return Marriage(marriage);

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

And on a side note: if the Marriage method will always only be used to display data, and never to save, store or change data, then using POST is not the best choice. POST typically implies a call with side effects (save, store, change, or even delete), and in general it is best to stick to that convention.

这篇关于ASP.NET Core:从GET重定向到POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆