Question: Does RedirectToAction only work for HttpGet?

Question

Does RedirectToAction only work for HttpGet?

Answers 1
Added at 2016-12-28 00:12
Tags
Question

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();
}
Answers
nr: #1 dodano: 2016-12-28 00:12

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.

Source Show
◀ Wstecz