自定义会员系统 mvc5 的未经身份验证的用户重定向

Unauthenticated user redirection for a custom membership system mvc5

我正在使用 mvc5 开发一个 erp 系统。我建立了自己的会员系统和用户,一旦用户登录,他的用户权限就保存在会话变量中。我想授权部分几乎完成了。但是对于身份验证,我现在试图限制未经身份验证的用户的访问。我这样试过

在我的 web.config

<authentication mode="Forms">
<forms loginUrl="~/Login/Login" timeout="2880" />
</authentication> 

我在控制器上放置了 [Authorize] 属性。

这适用于未经身份验证的用户。他们被重定向到登录页面。但这也限制了经过身份验证的用户的访问。(这意味着未经身份验证和经过身份验证的用户都不能访问具有授权属性的控制器)。

如果我删除授权属性,它会给我一个错误,因为没有要分配给会话变量的用户。这意味着没有授权属性 未经身份验证的用户可以访问控制器,即使 web.config 已被修改。

我认为这涉及创建自定义属性。但我不知道如何处理这个。所有帮助表示赞赏。提前致谢!

经过研究,我想出了解决方案。 我创建了一个自定义授权属性。

public class CustomAuthorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authroized = base.AuthorizeCore(httpContext);

        // Now check the session:
        var myvar = httpContext.Session["User"];
        if (myvar == null)
        {
            // the session has expired
            return false;
        }

        return true;
    }
}

在我的控制器上,我放置了 [CustomAuthorize],而不是 [authorize]。

在web.config

<authentication mode="Forms">
<forms loginUrl="~/Login/Login" timeout="2880" />
</authentication>