Search code examples
asp.net-mvccontrolleractionrestrict

ASP.NET MVC controller action restricted to a specific view


Is there a way to restrict a controller action to be accessible only from a specific view? I have a Details page for a queried entity in my database and basically by a button and a simple JS confirmation prompt I would like to change few properties of this object and save it back to the database. I've developed a controller action method which does the job but I have no idea how to restrict access to it, so users cannot (un)intentionally modify entities by passing a specific url in the browser. I would like the action to be only accessible on this specific Details page, by pressing the designated button. I tried using [ChildActionOnly] but it's only accessible from another action method, and not a view.

Thank you for your help.


Solution

  • Thanks to Stephen Muecke's comment I've managed to get it working.

    The button is a simple Action Link, which redirects to the restricted controller action:

    public ActionResult ReturnBook(int id)
        {
            if (Request.UrlReferrer == null)
            {
                return HttpNotFound();
            }
    
            //code
        }
    

    The method checks, if there is any UrlReferrer at all. Typing action url in the browser results in the referrer being null. If the call is made by ActionLink from a View, the UrlReferrer is not null and optionally its property Request.UrlReferrer.AbsolutePath can be checked and compared to a desired url, from which the invoke can only be made. In my case, as I am not invoking this method anywhere else in my code, I stayed with just null/notnull condition.