Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net mvc How to prevent browser from calling an action method?

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.

like image 464
Amir Jalali Avatar asked Feb 23 '12 04:02

Amir Jalali


1 Answers

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:

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

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

If you can't make the Index action a child action, you could always check the referrer, understanding that it's not foolproof and can be spoofed. See:

How do I get the referrer URL in an ASP.NET MVC action?

like image 118
Eric King Avatar answered Oct 03 '22 12:10

Eric King