kaivalya
kaivalya

Reputation: 3869

MVC redirect problem

I'm implementing a class for all my controllers to inherit that will redirect to login page if user is not authenticated. The RedirectToAction line is not redirecting though. Can you plesae help correct?

public class SecureController : Controller
    {
        public SecureController()
        {
            if (User == null || !User.Identity.IsAuthenticated)
            {
                RedirectToAction("Logon", "Account");
            }
        }
    }

Upvotes: 0

Views: 274

Answers (1)

mkchandler
mkchandler

Reputation: 4758

My suggestion would be to use an ActionFilter instead. It will be much easier. You can do something like this:

public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // You can do any custom authentication logic in here

        if (User == null || !User.Identity.IsAuthenticated)
        {
            // This assumes that Account is the controller, and Logon is the action method.
            // You might want to check your routes if this is still not working correctly
            RedirectToAction("Logon", "Account");
        }
    }
}

This will let you then just put an attribute on your action method in your controller like so:

[RequiresAuthentication]
public ActionResult Index()
{
    return View();
}

Or, as others have pointed out, if you do not need any custom authentication logic, you can just use the AuthorizeAttribute:

[Authorize]
public ActionResult Index()
{
    return View();
}

Upvotes: 1

Related Questions