简体   繁体   中英

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

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
}

ASP.NET Core has a new feature View Components . View components consists of two parts, a class and a result(typically a razor view). View components are not reachable directly as an HTTP endpoint, they are invoked from your code (usually in a view). They can also be invoked from a controller which best suits your need. Create a razor view for the success message

<h3> Success Message <h3>
Your Success Message...

Create the corresponding view component

public class SuccessViewComponent : ViewComponent
{
   public async Task<IViewComponentResult> InvokeAsync()
   {
       return View();
   }
}

Note that, the view name and the view component name and paths for those files follow a convention very similar to the controller and views. Refer to the ASP.NET core documentation for the same.

Invoke the view component from your action method

public IActionResult DoSomething()
{
    bool success=someWork();
    if(success)
    {
        return ViewComponent("Success");
    }
    else
    {
        return View();
    }
}

You could just make the action private.

public IActionResult DoSomething()
{
    bool success = someWork();
    if (success)
    {
       // goto some action but not allow that action to be called directly
       return MyCrazySecretAction();
    }
    else
    {
       return View();
    }
}

private IActionResult MyCrazySecretAction()
{
    return View();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM