MVC 5授权属性

时间:2017-06-15 14:33:54

标签: c# asp.net asp.net-mvc

我正在使用MVC 5 for ASP.NET。

我正在尝试创建自定义授权属性。使用OpenId并且存在会话变量时,用户通过我的应用程序进行身份验证。我已将[OpenIdAuthorize]添加到我的控制器中。当我在登录后查看它们时,我会在我的应用程序中退回到/ openid / index。会话变量存在。我添加了断点,但它们永远不会到达。

public class OpenIdAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Session["FriendlyEmail"] == null)
            return false;
        else
            return true;
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if(filterContext.HttpContext.Session["FriendlyEmail"] == null)
            filterContext.Result = new RedirectResult("/openid/index");
    }
}

这是我的控制器:

[OpenIdAuthorize]
public class RuleSetController : Controller

1 个答案:

答案 0 :(得分:1)

这是我的解决方案:

  1. 请勿在filter.config中输入任何内容。
  2. 在web.config中输入以下代码:(请参阅身份验证模式>表单https://support.microsoft.com/en-us/help/301240/how-to-implement-forms-based-authentication-in-your-asp.net-application-by-using-c-.net
  3. 调整AuthorizeAttribute以仅覆盖AuthorizeCore。不要覆盖其他方法。

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Session["FriendlyEmail"] == null)
            return false;
        else
            return true;
    }