RedirectToAction只适用于HttpGet吗?

时间:2016-12-27 23:38:26

标签: c# asp.net razor

我正在使用asp.net核心剃刀引擎。我正在重定向到另一个函数,当我发送给它的函数是HttpPost时,它无法正常工作。当我把它改成HttpGet时一切正常。这是为什么?

这是我的代码

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

1 个答案:

答案 0 :(得分:2)

语句return RedirectToAction将使用位置标题中的新网址向浏览器发送302响应,浏览器将为该网址发出新的GET请求。如果您是操作方法仅标有HttpPost属性,则它不适用于GET请求。因此,简而言之,您的Win操作不应使用[HttpPost]操作进行标记。