3

I am using .NET Core MVC to prevent users from navigating to an action by manually entering the URL into their browser.

In previous versions of MVC the following code snippet would do the trick:

public ActionResult Index()
{
    if(!ControllerContext.IsChildAction)
    {
        // redirect to different action
    }
    return View(viewModel);
}

Source (also similar question)

How could I accomplish this using .NET Core MVC?

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
Miguel J.
  • 337
  • 1
  • 16
  • My primary goal is to make sure a user can't accidentally browse to the action and trigger it. Sometimes browsers automatically populate the URL, causing the user to accidentally trigger the action. To mitigate this, which is probably the correct way to handle this, I made the action post only. – Miguel J. Dec 20 '18 at 21:31
  • 1
    IMO, you could not identify whether the request is from entering browser to clicking button. And for entering browser to access action is a feature for quickly access action. Not sure how will you access the specific method, you may consider adding header while sending request, and then check the request header in action to check whether it is from brower. – Edward Dec 24 '18 at 03:27

2 Answers2

3

Goodbye Child Actions, Hello View Components:

child Actions do not exist in ASP.NET Core MVC. Instead, we are encouraged to use the new View Component feature to support this use case.

Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137
  • 3
    Actually placing the example in that link into the answer itself. If the link dies (which i probably will, this answer will be mostly useless). [When someone goes on Stack Exchange, the question "answer" should actually contain an answer. Not just a bunch of directions towards the answer.](https://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers). – Erik Philips Dec 20 '18 at 22:00
  • 1
    @ErikPhilips, good feedback, thanks... I think the relevant part of the link is the quote that I have included in the answer: "child Actions do not exist in ASP.NET Core MVC... " If the question was: How should I implement View Component? then yes, the example would be necessary. – Hooman Bahreini Dec 20 '18 at 23:28
3

Child actions is not exist in ASP.NET Core MVC as mentioned in previous answer. View Component feature is just like child actions. Specified as "much powerful" in official documentation.

View Components are not reachable directly from browser. According to this, you dont need to control the request is comes from url or not.

View Component class creation types:

1) Creation with adding ViewComponent Suffix to class:

public class SampleViewComponent
{
    ...
}

2) Creation with deriving from ViewComponent:

public class Sample : ViewComponent
{
    ...
}

3) Creation with ViewComponent Attribute

[ViewComponent]
public class Sample
{
    ...
}
akaraca
  • 56
  • 2