简体   繁体   中英

How to check if controller context is child action in ASP.NET Core MVC?

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?

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.

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
{
    ...
}

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