Is Asp.Net Core redirected to an action, but doesn’t allow you to directly invoke an action?

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

For example, when someWork returns true, I would like to show a “successful page” with some data, but when it is false, I will return to the page and show errors.

Normally ChildAction will be able to do this, but they do not seem to be in .Net Core.

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

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

One solution (or rather a workaround) is to use temporary data to store the 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 } 
+3
source

ASP.NET Core has the new View Components feature . Viewing components consist of two parts, a class and a result (usually this is a kind of razor). View components are not directly accessible as an HTTP endpoint; they are called from your code (usually in the form). They can also be called from the controller that best suits your needs. Create a razor view to report success

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

Create the appropriate view component

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

Please note that the name of the view and the name of the component and path for these files follow a standard very similar to the controller and views. Refer to the basic ASP.NET documentation for the same.

Call a view component from your action method

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

You can 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(); } 
0
source

Source: https://habr.com/ru/post/1263905/


All Articles