Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Core redirect to action but not allow action to be called directly?

I have a situation where I want to redirect/show to some url/action when the result is successful but return to view if there was some error.

For example when someWork return true I would like to show "successful page" with some data but when it is false I would return to page and show errors.

Usually ChildAction would be able to do it, but in .Net Core they seem to be missing.

What would be the best way to achieve this? My main concern is that the "success" route/action should not be directly accessible if someone writes it in browser bar.

public IActionResult DoSomething()
{
    bool success = someWork();
    if (success)
    {
       // goto some action but not allow that action to be called directly
    }
    else
    {
       return View();
    }
}
like image 800
knowledgeseeker Avatar asked Feb 07 '17 06:02

knowledgeseeker


1 Answers

One solution (or rather a workaround) is to use temp data to store a bool and check it in your other action. Like this:

public IActionResult DoSomething()
{
    bool success=someWork();
    if(success)
    {
        TempData["IsLegit"] = true;
        return RedirectToAction("Success");
    }
    else
    {
        return View();
    }
}

public IActionResult Success
{
    if((TempData["IsLegit"]??false)!=true)
        return RedirectToAction("Error");
    //Do your stuff
}
like image 170
Emad Avatar answered Oct 04 '22 21:10

Emad