Tom
Tom

Reputation: 1334

Can an attribute be made that can redirect to an action?

I have an MVC3 web application with a front end and a backend. In the backend, each action is protected with an if..then..else redirecting to another action if the user is not logged in (it checks a session). It does this without windows roles.

I was wondering if it was possible to create an attribute that does the check and redirects the user to a login page without having to insert the same code over and over into each action?

EDIT #1

I've created a basecontroller which my admin controllers derived from and added the following member following on from what Virus said:

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        try
        {
            if (Session["loggedIn"] == null || (bool)Session["loggedIn"] != true)
            {
                TempData["targetAction"] = ControllerContext.ParentActionViewContext.RouteData.Values["action"] + "/" + ControllerContext.ParentActionViewContext.RouteData.Values["controller"];
                RedirectToRoute("Admin/Login");
            }
        }
        catch (NullReferenceException)
        {
            RedirectToRoute("Admin/Login");
        }
    }

But this code does'nt work. Can someone please tell me what is wrong?

Upvotes: 0

Views: 238

Answers (2)

Virus
Virus

Reputation: 2541

you can do this easily.

No need to use attributes

Just create a common BaseController which is inherited from Controller class, and inherit all your controllers from BaseController

override the OnActionExecuting event in BaseController and put the authorization logic on that.

the OnActionExecuting event will be executed every time when an action is invoked.

If you need to redirect to an Action, this code will help

filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "action", "Index" }, { "controller", "Account" } });

Upvotes: 6

VJAI
VJAI

Reputation: 32768

That's what the built-in AuthorizeAttribute filter does.

You can use the AuthorizeAttribute filter at a global level, controller level or even at action level. If the built-in Authorize filter is not enough for you can easily create a custom one by inheriting it as explained in this post.

Upvotes: 0

Related Questions