0

I am using asp.net core the razor engine. I am redirecting to another function and it was not working when the function I sent it to was a HttpPost. When I changed it to HttpGet everything worked fine. Why is this?

Here is my code

static bool init = false;
// GET: /Home/
[HttpGet]
[Route("")]
public IActionResult Index()
{
    if(init == false){
        HttpContext.Session.SetString("Happiness", "190");
        HttpContext.Session.SetString("Fullness", "190");
        HttpContext.Session.SetString("Energy", "190");
        HttpContext.Session.SetString("Meal", "3");
        HttpContext.Session.SetString("Message", "");
        HttpContext.Session.SetString("Tree", "/images/regular_tree.jpeg");
        init = true;
    }
    ViewData["Tree"] = HttpContext.Session.GetString("Tree");
    ViewData["Happiness"] = HttpContext.Session.GetString("Happiness");
    ViewData["Fullness"] = HttpContext.Session.GetString("Fullness");
    ViewData["Energy"] =  HttpContext.Session.GetString("Energy");
    ViewData["Meal"] =  HttpContext.Session.GetString("Meal");
    ViewData["Message"] =  HttpContext.Session.GetString("Message");

    if( Int32.Parse(HttpContext.Session.GetString("Happiness")) >= 100 &&
    Int32.Parse(HttpContext.Session.GetString("Fullness")) >= 100 &&
    Int32.Parse(HttpContext.Session.GetString("Energy")) >= 100){
        System.Console.WriteLine("WinFunction");
        System.Console.WriteLine("WinTwice");
        return RedirectToAction("Win");
    }
    return View();
}

[HttpGet]
[Route("win")]
public IActionResult Win()
{
    System.Console.WriteLine("Win");
    return View();
}
Aaron
  • 4,380
  • 19
  • 85
  • 141
  • [This page](http://stackoverflow.com/questions/129335/how-do-you-redirect-to-a-page-using-the-post-verb#answer-1343182) contains an interesting workaround that you may be able to use. – Dan Wilson Dec 28 '16 at 00:07

1 Answers1

2

The statement return RedirectToAction will send a 302 response to the browser with the new url in the location header, and browser will issue a new GET request for that url. If you are action method is only marked with HttpPost attribute, it will not work for a GET request. So in short, your Win action should not be marked with [HttpPost] action.

Shyju
  • 214,206
  • 104
  • 411
  • 497