tags:

views:

164

answers:

2

I have a the following methods in an MVC Controller which redirect to the login page when a user is not logged in.

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

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

Is there a quick/easy/standard way to redirect the second action to a different login page other than the page defined in the web.config file?

Or do I have to do something like

public ActionResult Edit() {
  if (IsUserLoggedIn)
    return View();
  else 
     return ReturnRedirect("/Login2");
}
A: 

Web.config based forms authentication does not have such a functionality built-in (this applies to both WinForms and MVC). You have to handle it yourself (either through an HttpModule or ActionFilter, the method you mentioned or any other method)

Mehrdad Afshari
+4  A: 

I think it is possible by creating a custom authorization filter:

public class CustomAuthorization:AuthorizeAttribute
        {
        public string LoginPage { get; set; }

            public override void OnAuthorization(AuthorizationContext filterContext)
            {
                if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    filterContext.HttpContext.Response.Redirect(LoginPage);
                }
                base.OnAuthorization(filterContext);
            }
        }

In your action:

[CustomAuthorization(LoginPage="~/Home/Login1")]
public ActionResult Search() {
  return View();
}

[CustomAuthorization(LoginPage="~/Home/Login2")]
public ActionResult Edit() {
  return View();
}
Marwan Aouida
Nice solution. I was unaware you can do this. http://www.asp.net/LEARN/mvc/tutorial-14-cs.aspx has a good introduction to creating custom Action Filters for people who want an explanation.
David G