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

how to prevent direct url access in asp.net mvc
prevent url tampering in asp.net mvc
how to prevent a file from direct url access c#
mvc call non action method from view
how to call controller method in mvc
mvc call post action from controller
call url from mvc controller
action methods 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.

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?

Asp.net mvc How to prevent browser from calling an action method , Hello, We have a ASP.net MVC application (Angular plus MVC) which calling your API. again CSRF is only to prevent browser based hacks. After using [ChildActionOnly] attribute, we restrict the action method to be called only from the View not directly by giving url in the browser address bar. Download 100% FREE Office Document APIs for .NET

Try making this Index controller action as private. A method with private access modifier should not be accessible from outside class.

And then, rahter than calling RedirectToAction from AddToCart call it as simple method like below:

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


public ActionResult AddToCart(int id)
{

    return Index();

}

ASP.net MVC action methods to restrict only to the same application , I have two actions inside my controller (shoppingCartController) public ActionResult Index() { //some stuff here return View(viewModel); } public ActionResult  In the HTTP post request, we look at the following code in view and controller several times: Called in 1.View Html.AntiForgeryToken ()。 2. The [validate anti forgery token] annotation is added to the method in the controller. This seemingly one-to-one writing is actually to avoid introducing Cross Site Request Forgery (CSRF) attacks. This form of …

If all you are worried about is the user typing in the URL, then using the HttpPost attribute should prevent your action from being called that way:-

[HttpPost]
public ActionResult AddToCart(int id)
{

This prevents GET requests from calling that action. It doesn't however stop someone writing a dummy form and POSTing to your action.

If you are worried about something a little more malicious, you might want to implement some form of anti-forgery token, there's some good info on that here.

EDIT

OK, so on re-reading the question the above doesn't quite address your issue.

How about a route? if you had something like the below, it would prevent ShoppingCart/Index being called and redirect the user to your site index.

        routes.MapRoute(
            "ShoppingCartIndex",
            "ShoppingCart/Index",
            new { controller = "Home", action = "Index" }
        );

Prevent Url Tampering in Asp.net MVC, It is based on Asp.Net MVC 5 using Ninject IOC container. to users; the simpler the urls are in browser address bar, the easier to forge it. the type of resource from the action method's parameter list and then call a service  Public non-action methods in ASP.NET MVC controllers are source of problems because they can be called by user when not handled carefully. Same time you may need public methods on controllers for some other reasons (some UI framework, testability problems, things you cannot change etc). In this posting I will show you how to handle controller methods properly.

If SessionState is enabled, you can use controller's TempData to achieve your goal. Set TempData in AddToCart action, and only display Index view if Index action can get TempData key set in AddToCart action.

If you need this for multiple actions/projects, use combination of custom Action Filter and ActionResult. Like this:

// Controller
[PreventDirectAccess]
public ActionResult Index()
{
    //some stuff here
    return View(viewModel);
}

public ActionResult AddToCart(int id)
{
    return new PreventDirectAccessRedirectToRouteResult(new RouteValueDictionary
    {
        {"action", "Index"}
    });
}

// Filter
public class PreventDirectAccessAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext == null)
            throw new ArgumentNullException("filterContext");

        if (filterContext.Controller.TempData[PreventDirectAccessRedirectToRouteResult.Executed] == null)
            filterContext.Result = new HttpNotFoundResult();

        base.OnActionExecuting(filterContext);
    }
}

// ActionResult
public class PreventDirectAccessRedirectToRouteResult : RedirectToRouteResult
{
    public const string Executed = "PreventDirectAccessRedirectExecuted";

    public override void ExecuteResult(ControllerContext context)
    {
        context.Controller.TempData[Executed] = true;
        base.ExecuteResult(context);
    }
}

URL Access: How to Prevent Direct URL Access In MVC, no direct access mvc prevent, how to restrict direct url access in mvc, how to prevent direct url access in asp.net mvc, mvc prevent url tampering, prevent direct url access mvc. We have to call this feature under OnActionExecuting of Action filter. are tempering URL in browser then it will forcibly throw you to Logout action  The traditional MVC pattern is still visible in ASP.NET Core, made up of the action/controller, the view, and the application model. Figure 5 A complete MVC request for the list of ToDos in the “Simple” category for user “Andrew”

Here is written code how to prevent browser direct access to action method: Write below code in FilterConfig.cs

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class NoDirectAccessAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.UrlReferrer == null ||
                    filterContext.HttpContext.Request.Url.Host != filterContext.HttpContext.Request.UrlReferrer.Host)
            {
            filterContext.Result = new RedirectToRouteResult(new
                           RouteValueDictionary(new { controller = "Home", action = "Index", area = "" })); 
        }
    }
}

Now apply this code on your action method

[NoDirectAccess]
public ActionResult MyActionMethod()

This will restrict to call directly any class or action method.

ASP.NET MVC: Using NonActionAttribute to restrict access to public , ASP.NET MVC: Using NonActionAttribute to restrict access to public methods of controller Public methods of controller are called controller actions and these actions are We can call this method directly through browser and if it contains To avoid users to invoke those methods directly – this can be  In ASP.NET MVC, View is funtionable with the help of Controller. All the incoming browser requests first come to the Controller and then the Controller will decide which action or view execute. View For WebForm Users. In ASP.NET webform, all the incoming browser requests come to ASPX file and file execute directly on browser very easily.

How to deal with browser back button click, a villain of web , So, if we want to execute the action method, we need to prevent browser from caching that page. Now, the question is how we will tell browser not  If all you are worried about is the user typing in the URL, then using the HttpPost attribute should prevent your action from being called that way:-[HttpPost] public ActionResult AddToCart(int id) { This prevents GET requests from calling that action. It doesn't however stop someone writing a dummy form and POSTing to your action.

Prevent Partial view to access directly in MVC, Prevent Partial view to access directly in MVC Now, you can check it out by the example, Just add the below lines of code in the controller action Even, if you can't access the Partial View result action method from ajax call as well. can identify the error in Console window of the browser is as follows. Now this time when the call goes to AddToCart method it goes by using ajax hence the whole page will not redirect or change, but its an asynchronous call which execute the AddToCart action method in your ProductController and the current page will remains same. Hence the product will also added to cart and page will not change to blank.

Routing in ASP.NET MVC – Programming with Wolfgang, NET MVC framework comes out of the box with a default route. You should keep this rule to prevent ASP.NET MVC If the user types into his browser myurl.​com/Home/Index the Index action in the Home controller is called. The second route calls an action entered in the Posts controller when the user  Now comes the second error, even if ASP.net could detect and convert it, it will still not work. Because of the point I described at 2 - Since you are using ASP.net MVC, it's not a good practice. The more conventional MVC way is to create routes and use those routes. Because in ASP.net you have the option to link to a page (.aspx, .ascx) directly.

Comments
  • if i put [ChildActionOnly] on my index method it wont be called from redirectToAction. it only works if i have html.action(). also controllerContext.ischildAction doesn't recognize redirecttoaction as childaction call.
  • If you want an action that works like a regular action (i.e. you can RedirectToAction to it) but can only be redirected to from one place, you could try to check the referer inside the action, redirecting to home/index if the referer isn't the AddToCart url. That wouldn't be foolproof, though, as referer can be spoofed.
  • i was going to check the response StatusCode. how should i check the referere?
  • stackoverflow.com/questions/1471188/…
  • i checked the Request.UrlReferrer it did't show which action it comes from it showed which url it comes from.
  • but it doesn't redirect the users to to home/index.
  • so it doesn't solve the problem of redirecting the user if they explicitly entered the url shoppingCart/Index it just gave the some error that the resources can not be found
  • Ok. What you have in Index should be some helper method which should be called from AddToCart. And Actual Index method should be public and shuld redirect to Home/Index.
  • I'd suggest using internal instead of private. That way it can still be made accessible to test projects.
  • I don't think it's the AddToCart action that he wants to protect, it's the Index action, which is a GET.
  • But you're right, the AddToCart action definitely needs to be a POST. :-)