ASP.NET Core: redirect from GET to POST

I want to call MarriageById as GET, like this:

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

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.

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

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.

Method 2

I don’t think you should mix GET with POST verbs. They are just semantically different.
If you have a similar functionality that you want to execute for those 2 methods, maybe instead of calling POST from GET you might want to extract the common parts ot some other ‘private’ method or even layer (depending on the use case).

Hope it makes sense


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x