Georgi-it
Georgi-it

Reputation: 3686

ASP.NET MVC 4 Make a page not directly reachable

I have a ASP.NET MVC 4 Blog which is 90% done but i need one thing - i have a webpage lets say index/secretPage but i want to be able to navigate to this webPage only after i am redirected from another - lets say index/redirect . If the adress is hardcoded it should not navigate, if the visitor is coming from a different link like blog/post/24 it should not be able to navigate too. I hope my question was clear, than you for all help.

Upvotes: 0

Views: 938

Answers (2)

DanielDüsentrieb
DanielDüsentrieb

Reputation: 23

You could also mask the secret page with an action that shows another page if direct called.

In this example there are 2 actions. 'Secret' for returning a bogus view and the 'Check' for the real call. In this action the bool variable 'allowSecret' ist checked an then the user sees the view 'secret.cshtml' if allowed or 'index.cshtml' if not.

Here's an example code for a simple controller with that functionality:

using System.Web.Mvc;

namespace Test.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View("Index");
        } 

        public ActionResult Check()
        {
            // check if user is allowed to show secret page
            if(allowSecret == true)    
                return View("Secret");
            // Otherwise return view 'index.cshtml' 
            return View();
        }

        public ActionResult Secret()
        {
            // Always shows view 'index.cshtml' if url is ".../secret"
            return View("Index");
        }        
    }
}

You could also redirect to another action after the check fails instead of calling a 'fake-view':

return RedirectToAction("Index")

The difference is the url the user sees in the browser. Returning a view does not change the url, redirecting to another action changes the url to the changed route.

Of course you can place the check in another class behind the controller.

Another option is to use the 'NonAction' attribute:

[NonAction]
public ActionResult Check()
{
   ...
}

Hope that helps with kind regards,

DD

Upvotes: 2

Guru Kara
Guru Kara

Reputation: 6472

You can UrlReferrer to get to know who refred to this current page and throw and exception or redirect back

HttpContext.Current.Request.UrlReferrer

http://msdn.microsoft.com/en-IN/library/system.web.httprequest.urlreferrer.aspx

But for what ever reason you need this. It dosenot look like a good design to me.

Hope this helps

Upvotes: 0

Related Questions