Q How can you prevent a cleint by using Action method in MVC?

I have two actions inside my controller (shoppingCartController)

public ActionResult Index()
{
	//some stuff here
	return View(viewModel);
}

public ActionResult AddToCart(int id)
{

	return RedirectToAction("Index");

}

Is there anyway to prevent the users from directly calling the index action by typing the url in the browser?
For example: If the user browses to shoppingCart/index be redirected to Home/Index.
Solution
You could use the [ChildActionOnly] attribute on your action method to make sure it’s not called directly, or use the ControllerContext.IsChildAction property inside your action to determine if you want to redirect.
For example:

//[ChildActionOnly]
public ActionResult Index()
{
    if(!ControllerContext.IsChildAction)
    {
       //perform redirect here
    }

    //some stuff here
    return View(viewModel);
}

Reference:
https://stackoverflow.com/questions/9407172/asp-net-mvc-how-to-prevent-browser-from-calling-an-action-method

 

Advertisements

Leave a comment

Filed under C#, Interview question, MVC, Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s