0

我正在关注下一篇文章,它确实是我正在使用的。

https://stackoverflow.com/a/15939899/1118485

如您所见,这仅在其中一种方法中实现HomeController。为了避免重写代码,我写了一个BaseController.

    protected new ViewResult View()
    {
        if (Session["sessionid"] == null )
        {
            //Session["sessionid"] = "empty";
            return base.View();
        }

        // check to see if your ID in the Logins table has LoggedIn = true - if so, continue, otherwise, redirect to Login page.
        if (OperationContext.IsYourLoginStillTrue(System.Web.HttpContext.Current.User.Identity.Name, Session["sessionid"].ToString()))
        {
            // check to see if your user ID is being used elsewhere under a different session ID
            if (!OperationContext.IsUserLoggedOnElsewhere(System.Web.HttpContext.Current.User.Identity.Name, Session["sessionid"].ToString()))
            {
                //return base.View();
            }
            else
            {
                // if it is being used elsewhere, update all their Logins records to LoggedIn = false, except for your session ID
                OperationContext.LogEveryoneElseOut(System.Web.HttpContext.Current.User.Identity.Name, Session["sessionid"].ToString());
                //return base.View();
            }
        }
        else
        {
            FormsAuthentication.SignOut();
            Attention("You have logged out because another user with the account has been connnected.");
            //return RedirectToAction("Login", "Account");
        }

        return base.View();
    }

但是正如你所看到的,这仅在使用View方法时才有效,在我的其他控制器中我使用了几个RedirectsFileResult. 所以我需要每一个ActionResult都被执行,验证上面的代码。当我被调查时,我认为我需要ActionResultAttribute在所有控制器中实现自定义,对吗?

如果我是对的,你能否向我展示一个演示实现,关于如何使用我的自定义ActionResultAttr来验证所有时间的登录。或者如果我错了,我该怎么办?

4

1 回答 1

0

您可以使用 Controller 类的 OnAuthorization 方法,该方法在操作之前执行。

public class BaseController : Controller
{
    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if ( /*session is not valid*/)
        {
            filterContext.Result = RedirectToAction("SessionExpired", "Account");
        }
    }
}
于 2013-06-01T23:42:21.450 回答