如何阻止用户在MVC3应用程序上登录/注册和其他非认证页面?

upd*_*dev 6 authentication asp.net-mvc login c#-4.0 asp.net-mvc-3

一旦用户登录到我使用表单身份验证的站点,如果他已经登录并注册,如何阻止用户进入登录和注册页面.

Cac*_*nta 5

如果用户已通过身份验证,并且是否将用户重定向到您想要的页面,那么最简单的方法是检入控制器方法(登录/注册):

登录页面的内容与此相同(与Register相同):

//
// GET: /Login/Index
public ActionResult Index()
{
     if(User.Identity.IsAuthenticated){
          //redirect to some other page
          return RedirectToRoute("Home", "Index"); 
     }

     return View();
}
Run Code Online (Sandbox Code Playgroud)


xan*_*ded 5

两种方式"脱离我的头脑":

1 -自定义Action Filter,如果用户已登录,则会将用户从页面重定向.

public class RedirectAuthenticatedRequests : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if(filterContext.HttpContext.Request.IsAuthenticated) {
            filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(new {
                        controller = "SomeController",
                        action = "SomeAction"
                }
            ));
        }

        base.OnActionExecuting(filterContext);
    }
}
Run Code Online (Sandbox Code Playgroud)

2 -login如果用户已登录,请简单检查操作方法.

if(Request.IsAuthenticated) return RedirectToAction("SomeOtherView");
Run Code Online (Sandbox Code Playgroud)